【发布时间】:2011-11-30 10:55:42
【问题描述】:
我不想创建新的 PDF 文件,我已经完成但想通过代码在 iOS 中显示和编辑现有的 pdf 文件..
这可能与否,如果可能的话,我该怎么做...
更新
假设会有文本文档 pdf,我们想在该文件中输入一些其他文本并保存它..那么如何通过编程来做到这一点?
请帮我解决这个问题...
提前谢谢...
【问题讨论】:
标签: iphone objective-c ios ipad pdf
我不想创建新的 PDF 文件,我已经完成但想通过代码在 iOS 中显示和编辑现有的 pdf 文件..
这可能与否,如果可能的话,我该怎么做...
更新
假设会有文本文档 pdf,我们想在该文件中输入一些其他文本并保存它..那么如何通过编程来做到这一点?
请帮我解决这个问题...
提前谢谢...
【问题讨论】:
标签: iphone objective-c ios ipad pdf
我能够通过创建原始 PDF 的副本并在构建过程中对其进行修改来做到这一点。
PS:在我的解决方案中,我需要编辑新 PDF 的文档信息,所以我使用了 执行此操作的主题参数。
在 Swift 3
func createPDF(on path: String?, from templateURL: URL?, with subject: String?) {
guard let newPDFPath = path,
let pdfURL = templateURL else { return }
let options = [(kCGPDFContextSubject as String): subject ?? ""] as CFDictionary
UIGraphicsBeginPDFContextToFile(newPDFPath, .zero, options as? [AnyHashable : Any])
let templateDocument = CGPDFDocument(pdfURL as CFURL)
let pageCount = templateDocument?.numberOfPages ?? 0
for i in 1...pageCount {
//get bounds of template page
if let templatePage = templateDocument?.page(at: i) {
let templatePageBounds = templatePage.getBoxRect(.cropBox)
//create empty page with corresponding bounds in new document
UIGraphicsBeginPDFPageWithInfo(templatePageBounds, nil)
let context = UIGraphicsGetCurrentContext()
//flip context due to different origins
context?.translateBy(x: 0.0, y: templatePageBounds.height)
context?.scaleBy(x: 1.0, y: -1.0)
//copy content of template page on the corresponding page in new file
context?.drawPDFPage(templatePage)
//flip context back
context?.translateBy(x: 0.0, y: templatePageBounds.height)
context?.scaleBy(x: 1.0, y: -1.0)
// -->>>> Do your change here <<<<--
/* Here you can do any drawings */
}
}
UIGraphicsEndPDFContext()
}
【讨论】:
我知道这个问题为时已晚,但我想添加我的解决方案。
我正在使用UIGraphicsBeginPDFContextToFile 生成 PDF 文件。我从基类UIViewController 创建了一个名为PDFCreator 的类,因为我有两个这样的函数:
- (void) beginContextWithFile:(NSString *)filename
{
pageSize = CGSizeMake(1024, 1424);
UIGraphicsBeginPDFContextToFile(filename, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
[self createInitialPart];
}
- (void) endContext
{
UIGraphicsEndPDFContext();
}
我在应用程序委托文件中创建了此类的一个对象,因为它将保留该对象直到应用程序终止(这是我的要求)。
最初,我调用beginContextWithFile:,它将在文档目录中创建一个pdf文件以及我通过调用createInitialPart方法添加的数据。
稍后我需要更新该文件,因此我有另一个名为 secondPart 的方法,尽管我调用它是为了将更多数据附加到该文件。
完成创建后,我需要调用 PDFCreator 类的 endContext,这将完成 pdf 生成,是的,我将获得更新的文件。
这有点棘手,虽然我有要求,但我没有执行任何内存检查,我找到了解决方案:)
【讨论】:
beginContextWithFile 将为我制作一个PDF 文件,但在我不调用endContext 方法之前不会保存它。我需要在哪里,我在一个班级中调用beginContextWithFile,经过一些更新,我确实调用了endContext 方法。
【讨论】: