将解锁PDFDocumentsRef保存到本地目录

时间:2015-02-16 08:09:40

标签: ios objective-c pdf cgpdfdocument cgpdfdocumentref

我正在使用我的新iPhone应用程序中的pdf。我正在检查PDF是否锁定(密码保护)

BOOL bIsUnlock = CGPDFDocumentIsUnlocked(PDFDocument);

如果pdf已锁定,则

BOOL success = CGPDFDocumentUnlockWithPassword ( PDFDocument, [password UTF8String]);

在这里,我成功解锁了文档。 现在我想将解锁文档保存到app目录。

我搜索并找到了一种方法

CGPDFPageRef _PDFPage =CGPDFDocumentGetPage(PDFDocument, 1);

CGRect pageRect = CGPDFPageGetBoxRect(_PDFPage, kCGPDFMediaBox);

//create empty pdf file;
UIGraphicsBeginPDFContextToFile(newFilePath, pageRect, nil);
size_t count = CGPDFDocumentGetNumberOfPages(PDFDocument);

for (size_t pageNumber = 1; pageNumber <= count; pageNumber++)

{

    //get bounds of template page

    CGPDFPageRef templatePage = CGPDFDocumentGetPage(PDFDocument, pageNumber);

    CGRect templatePageBounds = CGPDFPageGetBoxRect(templatePage, kCGPDFCropBox);

    //create empty page with corresponding bounds in new document
    UIGraphicsBeginPDFPageWithInfo(templatePageBounds, nil);

    CGContextRef context = UIGraphicsGetCurrentContext();

    //flip context due to different origins
    CGContextTranslateCTM(context, 0.0, templatePageBounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    //copy content of template page on the corresponding page in new file
    CGContextDrawPDFPage(context, templatePage);

    //flip context back
    CGContextTranslateCTM(context, 0.0, templatePageBounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0); 
 }
CGPDFDocumentRelease(PDFDocument);

UIGraphicsEndPDFContext(); 

但是我想要任何其他简单的方法,比如将PDFDocument转换为NSdata并保存到目录。 请帮忙。

2 个答案:

答案 0 :(得分:1)

遗憾的是,您的代码是将解密的PDF文件保存到应用目录的最简单的解决方案。问题是此代码仅适用于简单的PDF文件,因为注释,链接,表单字段,书签,文件附件等不会传输到新文档。这是CGPDF API的限制,你无能为力。

答案 1 :(得分:1)

正如iPDFdev已经提到的那样,你在这里与Apple的CoreGraphics渲染引擎相差甚远 - 你可能需要自己重新实现这一点。由于您可能没有几年时间这样做,因此有一些产品可以帮助您修改文档。

在开源前端有PoDoFo或muPDF(GPL /商业广告)可能能够解决您的问题。我使用商业PSPDFKit SDK,它允许您使用PSPDFProcessor重写文档 - 我们也为Android提供类似的API。