将UIImage转换为PDF文件

8
我正在尝试将UIImage保存为PDF文件。我该怎么做?我如何将图像保存到PDF文件中,然后导出该PDF文件?请为我提供解决此问题的方法。
谢谢。

为什么?虽然可能可以,但PDF被优化用于存储文档和矢量图形,而UIImage是位图... - kennytm
4个回答

15

你好,我发现这个方法有效,希望能帮到你!

-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
    {
        // Creates a mutable data object for updating with binary data, like a byte array
        NSMutableData *pdfData = [NSMutableData data];

        // Points the pdf converter to the mutable data object and to the UIView to be converted
        UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
        UIGraphicsBeginPDFPage();

        // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
        [aView.layer renderInContext:UIGraphicsGetCurrentContext()];

        // remove PDF rendering context
        UIGraphicsEndPDFContext();

        // Retrieves the document directories from the iOS device
        NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

        NSString* documentDirectory = [documentDirectories objectAtIndex:0];
        NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];

        // instructs the mutable data object to write its context to a file on disk
        [pdfData writeToFile:documentDirectoryFilename atomically:YES];
        NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
    }

似乎是一个不错的概念,但是生成了一个空白的PDF文件?在“aView”的drawRect方法中需要什么? - WrightsCS

3

我的理解是您将创建一个CGPDFContext,将您的UIImage绘制到其中,并将其保存到文件中。虽然我自己没有这样做过。


0

我也得到了一个空白的PDF。不过现在已经解决了。尝试更改:

//[aView drawRect:aView.bounds]; // <- This

[aView.layer renderInContext:UIGraphicsGetCurrentContext()]; // <- To This

-1

您可以启动一个PDF图形上下文,然后使用以下方式将图像绘制到其中:

[UIImage drawInRect: someRect];

您可以查看文档,它们对生成PDF文件有很好的解释。这里有一个关于PDF生成的好教程here


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