适用于不受支持的格式(.doc,.ppt,.xls等)的AirPrint有效,但有代码味道

时间:2013-10-28 13:00:13

标签: ios uiwebview nsurl tmp uiprintinteractioncntrler

使用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];
}

0 个答案:

没有答案