在iPhone上,是否有可能通过编程将多个PDF文件合并成单个PDF文件。我已经从程序的不同部分创建了单独的页面,现在需要将它们合并成一个文件。
是的,你可以这样做。请按照以下代码操作。
//Open a pdf context for the single file
UIGraphicsBeginPDFContextToFile(oldFile, paperSize, nil);
//Run a loop to the number of pages you want
for (pageNumber = 1; pageNumber <= count; pageNumber++)
{
//Open a pdf page context
UIGraphicsBeginPDFPageWithInfo(paperSize, nil);
//Get graphics context to draw the page
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//Flip and scale context to draw the pdf correctly
CGContextTranslateCTM(currentContext, 0, paperSize.size.height);
CGContextScaleCTM(currentContext, 1.0, -1.0);
//Get document access of the pdf from which you want a page
CGPDFDocumentRef newDocument = CGPDFDocumentCreateWithURL ((CFURLRef) newUrl);
//Get the page you want
CGPDFPageRef newPage = CGPDFDocumentGetPage (newDocument, pageNumber);
//Drawing the page
CGContextDrawPDFPage (currentContext, newPage);
//Clean up
newPage = nil;
CGPDFDocumentRelease(newDocument);
newDocument = nil;
newUrl = nil;
}
UIGraphicsEndPDFContext();
在绘制页面之前,您必须编写从适当的PDF中获取适当页面的必要条件。您已经从多个来源创建了一个PDF!
这是我编写的一个例程,它可以将PDF文件的URL添加到您已经创建的上下文中(这样您就可以调用它来处理多个文件并将它们全部附加):
- (void)appendPdfAtURL:(NSURL *)pdfURL toContext:(CGContextRef)pdfDestinationContext {
CGPDFDocumentRef pdfDoc = CGPDFDocumentCreateWithURL((__bridge_retained CFURLRef)pdfURL);
if (pdfDoc) {
size_t numPages = CGPDFDocumentGetNumberOfPages(pdfDoc);
if (numPages > 0) {
// Loop through each page in the source file
for (size_t i = 1; i <= numPages; i++) {
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDoc, i);
if (pdfPage) {
// Get the page size
CGRect pdfCropBoxRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);
// Copy the page from the source file to the context
CGContextBeginPage(pdfDestinationContext, &pdfCropBoxRect);
CGContextDrawPDFPage(pdfDestinationContext, pdfPage);
}
}
}
// Close the source file
CGPDFDocumentRelease(pdfDoc);
}
}
尝试使用Quartz 2D API。它对于读写PDF文件有非常好的支持。
请注意,PDF页面绘制代码应该在begin page和end page调用之间。
CGPDFDocumentCreateWithURL
CGContextBeginPage
CGPDFDocumentGetPage
CGPDFContextCreateWithURL
CGContextDrawPDFPage
CGContextEndPage
查看苹果文档以获取更多信息
[CGContext][1]
[CGPDFDocument][2]
[CGPDFPage][3]
看看这是否有帮助,或者如果您需要一些示例伪代码,请告诉我。
Swift 5 ## 简单全面的解释如何合并、转换和保存PDF
- FrugalResolution