iphone从pdf页面创建pdf文档

时间:2010-08-31 05:37:32

标签: iphone objective-c

我想从现有的pdf文档创建一个新的PDF文件。那就是我有一个pdf文件说“old.pdf”,并且从该用户可以选择一些页面,并从那些选定的页面我想要创建新的pdf文件说“temp1.pdf”。是否可以创建“temp1.pdf”? Plz帮助我,并提供一些代码示例来做到这一点。 感谢。

1 个答案:

答案 0 :(得分:0)

这是我的演示代码,你可以尝试一下。但是这段代码有一些问题。新生成的PDF出现乱码文本,我仍无法解决这个问题(有人可以帮忙吗?)。

//old pdf
NSArray* old_PDF_paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* old_PDF_documentsDirectory = [old_PDF_paths objectAtIndex:0];
NSString* old_PDF_ABSOLUTE_PATH = [old_PDF_documentsDirectory stringByAppendingPathComponent:@"old.pdf"];

//new generate pdf
NSArray* output_PDF_paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* output_PDF_documentsDirectory = [output_PDF_paths objectAtIndex:0];
NSString* output_PDF_ABSOLUTE_PATH = [output_PDF_documentsDirectory stringByAppendingPathComponent:@"temp1.pdf"];
NSString* outpath = output_PDF_ABSOLUTE_PATH;

NSURL *url = [[NSURL alloc] initFileURLWithPath:old_PDF_ABSOLUTE_PATH];
CGPDFDocumentRef originalPDF = CGPDFDocumentCreateWithURL((CFURLRef)url);

// query for the number of pages
int ct = CGPDFDocumentGetNumberOfPages(originalPDF);

CGFloat width = 0.0f;
CGFloat height = 0.0f;

CGRect outRect = CGRectMake(0, 0, width, height);
CFURLRef outurl = CFURLCreateWithFileSystemPath (NULL, (CFStringRef)outpath,  kCFURLPOSIXPathStyle, 0);
CFMutableDictionaryRef myDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); 

// create a context for drawing
CGContextRef context = CGPDFContextCreateWithURL ((CFURLRef)outurl, &outRect, myDictionary); // 5
CFRelease(myDictionary);

for(int i = 1; i <= ct; ++i) {
    //page render
    CGPDFPageRef pdfPage =  CGPDFDocumentGetPage(originalPDF, i);
    CGRect pageMediaBox = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox); 
    CGContextBeginPage (context, &pageMediaBox); 
    CGContextDrawPDFPage(context, pdfPage);
    CGContextEndPage (context); 
}

CGContextClosePath(context);
CGContextRelease(context);