在iPhone或iPad上打印PDF文件

10

我已经使用了这段代码将文件附加到邮件中。

[mail addAttachmentData:[myView PDFData] mimeType:@"application/pdf" fileName:@"name.pdf"];
我如何在打印文件时做相同的事情,我需要打印这个 [myView PDFData]。
我只找到了这个用于打印:
NSString *PDFFileWithName = [[NSBundle mainBundle] pathForResource:@"name" ofType:@"pdf"];

NSData *dataFromPath = [NSData dataWithContentsOfFile:PDFFileWithName];

感谢

4个回答

6
你应该仔细阅读iOS绘图和打印指南UIPrintInteractionControllerprintingItem属性可以设置为PDF的NSData

更新附加代码

dataFromPath的值应该等于[myView PDFData],但我建议在你让它工作后更改变量名。

NSData *dataFromPath = [myView PDFData];

这些是我用于电子邮件的代码(它运行得非常好),需要更改的是打印代码。 - Marco
我已经更新了我的回答,如果你愿意的话,你可以在帖子中编辑并重新发布你的代码示例。 - Joe
1
我用这段代码做到了,实际上很容易...谢谢大家: printController.printingItem = [myView PDFData]; - Marco

5

打印PDF的完整代码

UIPrintInteractionController *pc = [UIPrintInteractionController
                                        sharedPrintController];
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    printInfo.orientation = UIPrintInfoOrientationPortrait;
    printInfo.jobName =@"Report";

    pc.printInfo = printInfo;
    pc.showsPageRange = YES;
    pc.printingItem = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://test.com/Print_for_Client_Name.pdf"]];
    // You can use here image or any data type to print.


UIPrintInteractionCompletionHandler completionHandler =
^(UIPrintInteractionController *printController, BOOL completed,
  NSError *error) {
    if(!completed && error){
        NSLog(@"Print failed - domain: %@ error code %ld", error.domain,
              (long)error.code);
    }
};


[pc presentFromRect:CGRectMake(0, 0, 300, 300) inView:self.view animated:YES completionHandler:completionHandler];

3
请写下面的代码并检查它。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathFolder = [NSString stringWithFormat:@"%@",pdfFileName];
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:pathFolder];
NSURL *targetURL = [NSURL fileURLWithPath:path];

UIPrintInteractionController *pc = [UIPrintInteractionController sharedPrintController];
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.orientation = UIPrintInfoOrientationPortrait;
printInfo.jobName =@“Print”;
printInfo.duplex = UIPrintInfoDuplexLongEdge;

pc.printInfo = printInfo;
pc.showsPageRange = YES;
pc.printingItem = targetURL;

UIPrintInteractionCompletionHandler completionHandler =
    ^(UIPrintInteractionController *printController, BOOL completed,
      NSError *error) {
     if(!completed && error){
         NSLog(@"Print failed - domain: %@ error code %ld", error.domain, (long)error.code);
     }
};
[pc presentFromRect:shareButton.frame inView:self.view animated:YES completionHandler:completionHandler];

你能否在回答中加上为什么这段代码会解决问题的描述?只给出代码而不提供描述很少有助于未来的读者。 - Artjom B.

2

我知道那个教程,它很棒,但是我找不到我需要的东西。 - Marco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接