在iPhone上以编程方式创建PDF?

3

大家好,我想知道是否有人能够指导我。我对如何在iPhone上以编程方式创建PDF文件很感兴趣。文档提到了CGPDFDocumentCreateWithProvider,但我不确定如何使用它。谢谢!


这可能不正确,但我相当确定iPhone无法创建PDF,除非使用外部服务来生成文档。同样,我认为在没有外部服务呈现输出的情况下,在iPhone上查看PDF是不可能的。 - Nathan Taylor
试试这个:https://github.com/RobertAPhillips/UIView_2_PDF - Rob Phillips
3个回答

2
同样地,我不相信在iPhone上查看PDF文件而无需外部服务来呈现输出是可能的。
这是不正确的。您可以在UIWebView实例中呈现PDF文档,例如:
NSString *urlPathStr = [[NSBundle mainBundle] pathForResource:@"myPDFFile" ofType:@"pdf"];
NSURL *url = [NSURL fileURLWithPath:urlPathStr];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[myWebView loadRequest:urlRequest];

为了获得更好的性能,您还可以在UIView对象中呈现PDF。

目前iPhone尚未提供PDFKit库。

您可以查看QuartzDemo示例应用程序,了解一些用于呈现和操作PDF文档的Quartz2D方法。


1

你需要使用CGPDFDocumentCreateWithProvider或CGPDFDocumentCreateWithURL方法。

我尝试了CGPDFDocumentCreateWithURL方法。它将在你提供给该方法的URL中创建一个PDF文件作为第一个参数。

一旦创建完成,可以通过在Web视图中加载该URL来查看PDF文件。

你可以使用cgcontextRef类向PDF文件中添加内容。


0

这是你如何在iPhone应用程序中读取和存储本地PDF的方法:

首先创建UIWebView并包含<<UIWebViewDelegate>>

  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
  NSString *documentsPath = [paths objectAtIndex:0];
  NSString *filePath = [documentsPath stringByAppendingPathComponent:@"YourPDF.pdf"]; 
 if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
           // download file , here "https://s3.amazonaws.com/hgjgj.pdf" = pdf downloading link
         NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"https://s3.amazonaws.com/hgjgj.pdf"]];
            //Store the downloaded file  in documents directory as a NSData format
         [pdfData writeToFile:filePath atomically:YES];
    }

     NSURL *url = [NSURL fileURLWithPath:filePath];
     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
     [yourWebView setUserInteractionEnabled:YES];
     [yourWebView setDelegate:self];
     yourWebView.scalesPageToFit = YES;
     [yourWebView loadRequest:requestObj];

或者,如果你只是想从你的资源文件夹中读取/加载PDF文件,那么只需这样做:

     NSString*  filePath= [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"pdf"]];
    /// or you can even read docs file as : pathForResource:@"sample" ofType:@"docx"]
     NSURL *url = [NSURL fileURLWithPath:filePath];
     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
     [yourWebView setUserInteractionEnabled:YES];
     [yourWebView setDelegate:self];
     yourWebView.scalesPageToFit = YES;
     [yourWebView loadRequest:requestObj];

或者,如果你想从一堆文本和字符串创建自己的pdf,这是我是如何做到的: http://iosameer.blogspot.com/2012/09/creating-pdf-file-from-simple.html


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