使用this question中的提示,可以打印DOCX,PDF,...将其加载到UIWebView
:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
现在,为了获得filePath
,我将要打印的文档写入应用程序的tmp/
目录中:
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString* filePath = [NSString stringWithFormat:@"%@/%@.%@", NSTemporaryDirectory(), documentName, mimeType];
[fileManager createFileAtPath:filePath contents:documentData attributes:nil];
我只需要将NSData(文档)加载到UIWebView中即可打印出来。 我可以直接获取文档的filePath
(并避免写入磁盘)吗?
已经尝试[webView loadData:documentData MIMEType:mimeType textEncodingName:nil baseURL:nil];
及其变体。
整件事:
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];
}