我的目标是合并两个PDF。一个有10页,另一个有6页,所以输出应该是16页。我的方法是将两个PDF加载到存储在一个NSData
中的两个NSMutableArray
中。
以下是我的储蓄方法:
NSMutableData *toSave = [NSMutableData data];
for(NSData *pdf in PDFArray){
[toSave appendData:pdf];
}
[toSave writeToFile:path atomically:YES];
然而,输出PDF只有第二部分,它只包含6页。所以我不知道我错过了什么。有人能给我一些提示吗?
发布于 2018-02-15 22:06:58
PDF是一种描述单个文档的文件格式。无法连接到PDF文件以获得连接的文档。
但是可以通过PDFKit实现这一点
这看起来应该是:
PDFDocument *theDocument = [[PDFDocument alloc] initWithData:PDFArray[0]]
PDFDocument *theSecondDocument = [[PDFDocument alloc] initWithData:PDFArray[1]]
NSInteger theCount = theDocument.pageCount;
NSInteger theSecondCount = theSecondDocument.pageCount;
for(NSInteger i = 0; i < theSecondCount; ++i) {
PDFPage *thePage = [theSecondDocument pageAtIndex:i];
[theDocument insertPage:thePage atIndex:theCount + i];
}
[theDocument writeToURL:theTargetURL];
您必须将#import <PDFKit/PDFKit.h>
或@import PDFKit;
添加到源文件中,并且应该将PDFKit.framework
添加到Xcode中构建目标的链接框架和库中。
发布于 2020-02-04 08:57:04
我制作了一个Swift命令行工具来组合任意数量的PDF文件。它将输出路径作为第一个参数,而输入PDF文件作为其他参数。没有任何错误处理,所以您可以添加,如果您愿意。下面是完整的代码:
import PDFKit
let args = CommandLine.arguments.map { URL(fileURLWithPath: $0) }
let doc = PDFDocument(url: args[2])!
for i in 3..<args.count {
let docAdd = PDFDocument(url: args[i])!
for i in 0..<docAdd.pageCount {
let page = docAdd.page(at: i)!
doc.insert(page, at: doc.pageCount)
}
}
doc.write(to: args[1])
https://stackoverflow.com/questions/48820512
复制