使用下面的代码我成功写了pdf,但不是所有的文件!我可以看到该文档是3页,但只有一页正在写。有谁知道为什么?
(PresentationItem *)presentationItemFromDictionary:(NSDictionary *)dict {
if (dict == nil) return nil;
CGPDFDocumentRef document = [self newPdfDocumentFromBase64DataString:[dict objectForKey:@"base64"]];
NSString *tempName = [dict objectForKey:@"name"];
// Create the pdf context
CGPDFPageRef page = CGPDFDocumentGetPage(document, 1);
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CFMutableDataRef mutableData = CFDataCreateMutable(NULL,0);
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData(mutableData);
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &pageRect, NULL);
if(CGPDFDocumentGetNumberOfPages(document) > 0){
// Draw the page onto the new context
CGPDFContextBeginPage(pdfContext, NULL);
CGContextDrawPDFPage(pdfContext, page);
CGPDFContextEndPage(pdfContext);
}
else{
NSLog(@"Failed to create the document");
}
CGContextRelease(pdfContext);
// Write to disk
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"%@/%@.pdf", docDir,tempName];
[(__bridge NSData *)mutableData writeToFile:fileName atomically:YES];
PresentationItem *item = [[PresentationItem alloc] init];
[item setTitle:[dict objectForKey:@"name"]];
[item setDocument:document];
CGPDFDocumentRelease(document);
CGDataConsumerRelease(dataConsumer);
CFRelease(mutableData);
return item;
}
答案 0 :(得分:0)
尝试:
检查此代码..它将迭代所有页面&将每个页面写入pdfContext。然后保存文件。
if (dict == nil) return nil;
NSString *tempName = [dict objectForKey:@"name"];
CGPDFDocumentRef document = [self newPdfDocumentFromBase64DataString:[dict objectForKey:@"base64"]];
CGPDFPageRef page;
CFURLRef pdfURLOutput = (CFURLRef)[[NSURL alloc] initFileURLWithPath:YOUR_OUTPUT_FULL_FILE_PATH];
CGContextRef pdfContext = CGPDFContextCreateWithURL(pdfURLOutput, NULL, NULL);;
CGRect pageRect;
for (int i=1; i<=CGPDFDocumentGetNumberOfPages(document); i++)
{
page = CGPDFDocumentGetPage(document, i);
pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
CGContextBeginPage(pdfContext, &pageRect);
CGContextDrawPDFPage(pdfContext, page);
CGContextEndPage(pdfContext);
}
CGContextRelease(pdfContext);
// Write to disk
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"%@/%@.pdf", docDir,tempName];
[(__bridge NSData *)mutableData writeToFile:fileName atomically:YES];
PresentationItem *item = [[PresentationItem alloc] init];
[item setTitle:[dict objectForKey:@"name"]];
[item setDocument:document];
CGPDFDocumentRelease(document);
CGDataConsumerRelease(dataConsumer);
CFRelease(mutableData);
return item;