【问题标题】:Save PDF with password iOS使用密码保存 PDF iOS
【发布时间】:2013-11-08 14:38:56
【问题描述】:

我正在构建一个从服务器下载 PDF 文件、添加密码然后将文件保存到本地的应用程序。

我正在努力为文件添加设置密码。下面是我运行的设置密码和保存文件的函数。

- (void)addPassword:(NSString *)password forPDFAtPath:(NSString *)path {
NSData *data = [NSData dataWithContentsOfFile:path];

//Create the pdf document reference
CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((CFDataRef)data);
CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(dataProvider);

//Create the pdf context
CGPDFPageRef page = CGPDFDocumentGetPage(document, 1); //Pages are numbered starting at 1
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CFMutableDataRef mutableData = CFDataCreateMutable(NULL, 0);



CFMutableDictionaryRef ref = CFDictionaryCreateMutable(NULL,
                                                       0,
                                                       &kCFTypeDictionaryKeyCallBacks,
                                                       &kCFTypeDictionaryValueCallBacks);

CFDictionarySetValue(ref, kCGPDFContextUserPassword, (__bridge CFStringRef)password);
CFDictionarySetValue(ref, kCGPDFContextOwnerPassword, (__bridge CFStringRef)password);

CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData(mutableData);
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &pageRect, ref);

if (CGPDFDocumentGetNumberOfPages(document) > 0) {
    //Draw the page onto the new context
    page = CGPDFDocumentGetPage(document, 1); //Pages are numbered starting at 1

    CGPDFContextBeginPage(pdfContext, NULL);
    CGContextDrawPDFPage(pdfContext, page);
    CGPDFContextEndPage(pdfContext);

} else {
    NSLog(@"Failed to create the document");
}

CGContextRelease(pdfContext); //Release before writing data to disk.

//Write to disk
[(__bridge NSData *)mutableData writeToFile:path atomically:YES];

//Clean up
CGDataProviderRelease(dataProvider); //Release the data provider
CGDataConsumerRelease(dataConsumer);
CGPDFDocumentRelease(document);
CFRelease(mutableData);}

这确实设置了密码并保存文件,但只有一页。如何让它创建整个 PDF 的副本?

据我所知,这个脚本需要遍历所有页面并逐页绘制 PDF。有没有一种方法可以简单地复制 PDF 并设置密码,而不必绘制每一页?

提前致谢

【问题讨论】:

    标签: ios pdf


    【解决方案1】:

    在 iOS 上,您不能简单地复制文件并设置密码。您必须遍历源文档的所有页面并将它们绘制到新文档中。
    这种方法的问题是只有页面内容被传输到新文档。如果源文档包含书签、注释、表单域、附件,那么它们将不会被转移到新文档中。目前没有解决方案。

    【讨论】:

    • 感谢您的帮助。对我来说,没有复制 PDF 的方法似乎很愚蠢。
    猜你喜欢
    • 2016-09-30
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 2016-09-19
    • 2010-09-27
    相关资源
    最近更新 更多