2016-10-17 64 views
1

我刚刚将OS X更新到最新版本10.12(OS X Siarra),并破坏了以前的pdf生成代码。以下是我的PDF生成代码,它从给定的图像创建PDF文件。现在这个代码生成没有图像的PDF空白文件。在mac OS上使用PDFKit添加PDF图像时出现的问题Sierra

PDFDocument *pdf = [[PDFDocument alloc] init]; 
NSImage *image =[NSImage imageNamed:@"sample"]; 
PDFPage *page = [[PDFPage alloc] initWithImage:image]; 
[page setBounds:NSMakeRect(0, 0, 500,700) forBox:kPDFDisplayBoxMediaBox]; 
[pdf insertPage:page atIndex: [pdf pageCount]]; 
if([pdf writeToFile: fileName]){ 
      [self showAlert:@"Design pdf has been saved."]; 
     } 

此前这是以前版本中的工作代码。我在旧版本10.11上进行了测试,它也有效。任何建议什么是错误的或任何解决方法?

+0

的代码是正确的。我还没有升级到Sierra。应该管用。 – Tushar

+0

MacOS 10.12 PDFKit Sierra有许多问题和bug,但是这个代码在MacOS 10.12 Sierra上适用于我。 – danielv

+0

上面的代码工作和创建pdf文件..但图像不加起来。文字和其他东西也在起作用。 –

回答

1

在塞拉利昂有一个问题,图片在使用PDFKit添加到PDF文档时看到空白。您需要使用低级Quart 2D编程指南apis来获取正确的pdf。

Apple Documentation因为它在这里。

示例代码 -

CFStringRef path = CFStringCreateWithCString (NULL, filename,kCFStringEncodingUTF8); 
CFURLRef url = CFURLCreateWithFileSystemPath (NULL, path, kCFURLPOSIXPathStyle, 0); 
CFRelease (path); 


CFMutableDictionaryRef myDictionary = myDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); 
CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("Some property string")); 
CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("Some property string")); 
CFRelease(myDictionary); 


pageDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); 
CFDataRef boxData = CFDataCreate(NULL,(const UInt8 *)&pageRect, sizeof (CGRect)); 
CFDictionarySetValue(pageDictionary, kCGPDFContextMediaBox, boxData); 


CGContextRef pdfContext = CGPDFContextCreateWithURL (url, &pageRect, myDictionary); 
CGPDFDocumentRef document = CGPDFDocumentCreateWithURL (url); 
CFRelease(url); 

ViewController* currentView = [story instantiateControllerWithIdentifier:viewName]; 

NSImage *currentImage = [self imageRepresentation:currentView.view]; 

CGImageSourceRef source = CGImageSourceCreateWithData((CFDataRef)[currentImage TIFFRepresentation], NULL); 
CGImageRef maskRef = CGImageSourceCreateImageAtIndex(source, 0, NULL); 

CGPDFContextBeginPage (pdfContext, pageDictionary); 
CGContextDrawImage(pdfContext, pageRect, maskRef); 
CGPDFContextEndPage (pdfContext); 

CGContextRelease (pdfContext); 
CFRelease(pageDictionary); 
CGPDFDocumentRelease (pdfDocument); 
+0

谢谢Tushar!它像魅力一样工作! –