如何在不丢失任何信息的情况下合并两个 pdf?

How to combine two pdfs without losing any information?

我的目标是合并两个 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页。所以我不知道我错过了什么。谁能给我一些提示?

PDF 是一种描述单个文档的文件格式。您无法连接到 PDF 文件以获取连接后的文档。

但可以通过 PDFKit 实现:

  1. 使用 initWithData: 创建两个文档。
  2. 使用 insertPage:atIndex: 将第二个文档的所有页面插入到第一个文档中。

这应该是这样的:

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 添加到 Linked Frameworks and Libraries Xcode 中的构建目标。

我制作了一个 Swift 命令行工具来合并任意数量的 PDF 文件。它以输出路径作为第一个参数,以输入 PDF 文件作为其他参数。没有任何错误处理,因此您可以根据需要添加它。这是完整的代码:

import PDFKit

let args = CommandLine.arguments.map { URL(fileURLWithPath: [=10=]) }
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])