【发布时间】:2012-03-27 14:54:03
【问题描述】:
是否可以在 iphone 中以编程方式将多个 pdf 文件合并为一个 pdf 文件。我已经从程序的不同部分创建了单独的页面,现在需要将它们合并到一个文件中
【问题讨论】:
是否可以在 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 页面绘制代码应该在开始页面和结束页面调用之间
CGPDFDocumentCreateWithURL
CGContextBeginPage
CGPDFDocumentGetPage
CGPDFContextCreateWithURL
CGContextDrawPDFPage
CGContextEndPage
查看 Apple 文档
[CGContext][1]
[CGPDFDocument][2]
[CGPDFPage][3]
看看它是否有帮助,或者如果你需要一些示例伪代码,请告诉我。
【讨论】: