Using the hint in this question one can print DOCX, PDF, ... by loading it into UIWebView
:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
Now, to get the filePath
, I write the document-to-be-printed into app's tmp/
directory:
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString* filePath = [NSString stringWithFormat:@"%@/%@.%@", NSTemporaryDirectory(), documentName, mimeType];
[fileManager createFileAtPath:filePath contents:documentData attributes:nil];
I just need to load NSData (the document) into UIWebView in order to print it. Can I get the document's filePath
directly (and avoid writing the disk)?
Already tried [webView loadData:documentData MIMEType:mimeType textEncodingName:nil baseURL:nil];
and its variations.
The whole thing:
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
if (pic)
{
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlackOpaque];
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.jobName = documentName;
pic.printInfo = printInfo;
// Apple-supported formats (.pdf & some images)
if ([UIPrintInteractionController canPrintData:documentData])
pic.printingItem = documentData;
// Apple-un-supported formats (.doc, .xls, .ppt, ...)
else
{
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString* filePath = [NSString stringWithFormat:@"%@/%@.%@", NSTemporaryDirectory(), documentName, mimeType];
[fileManager createFileAtPath:filePath contents:documentData attributes:nil];
UIWebView* webView = [UIWebView new];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
pic.printFormatter = webView.viewPrintFormatter;
}
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
^(UIPrintInteractionController *pic, BOOL completed, NSError *error)
{
if (!completed && error)
NSLog(@"Printing error in domain %@ with error code %u", error.domain, error.code);
};
[pic presentAnimated:YES completionHandler:completionHandler];
}