我将我的代码从iPhone移植到Mac,我不知道如何在Mac上执行此操作。这是我试图转换的代码,我知道Mac中没有UIGraphic。有人能指点我指导或给我一个快速提示吗?感谢。
NSString *newFilePath = @"path/to/your/newfile.pdf";
NSString *templatePath = @"path/to/your/template.pdf";
//create empty pdf file;
UIGraphicsBeginPDFContextToFile(newFilePath, CGRectMake(0, 0, 792, 612), nil);
CFURLRef url = CFURLCreateWithFileSystemPath (NULL, (CFStringRef)templatePath, kCFURLPOSIXPathStyle, 0);
//open template file
CGPDFDocumentRef templateDocument = CGPDFDocumentCreateWithURL(url);
CFRelease(url);
//get amount of pages in template
size_t count = CGPDFDocumentGetNumberOfPages(templateDocument);
//for each page in template
for (size_t pageNumber = 1; pageNumber <= count; pageNumber++) {
//get bounds of template page
CGPDFPageRef templatePage = CGPDFDocumentGetPage(templateDocument, pageNumber);
CGRect templatePageBounds = CGPDFPageGetBoxRect(templatePage, kCGPDFCropBox);
//create empty page with corresponding bounds in new document
UIGraphicsBeginPDFPageWithInfo(templatePageBounds, nil);
CGContextRef context = UIGraphicsGetCurrentContext();
//flip context due to different origins
CGContextTranslateCTM(context, 0.0, templatePageBounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
//copy content of template page on the corresponding page in new file
CGContextDrawPDFPage(context, templatePage);
//flip context back
CGContextTranslateCTM(context, 0.0, templatePageBounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
/* Here you can do any drawings */
[@"Test" drawAtPoint:CGPointMake(200, 300) withFont:[UIFont systemFontOfSize:20]];
}
CGPDFDocumentRelease(templateDocument);
UIGraphicsEndPDFContext();
答案 0 :(得分:13)
使用CGPDFContextCreateWithURL
代替UIGraphicsBeginPDFContextToFile
(参数非常相似)。要开始/结束页面,请使用CGPDFContextBeginPage
和CGPDFContextEndPage
。完成后,请致电CGPDFContextClose
而不是UIGraphicsEndPDFContext
。
其余的可以保持不变 - 在iOS和Mac OS X上都存在Core Graphics - 这也意味着如果你想在两个平台上使用相同的代码,你也可以使用我在iOS上提到的功能
答案 1 :(得分:0)
Swift 4,macOS High Sierra更新
func generatePdfWithFilePath(thefilePath: String)
{
let url = URL(fileURLWithPath: thefilePath) as CFURL
guard let currentContext = CGContext(url, mediaBox: nil, documentInfo as CFDictionary) else {
return
}
self.context = currentContext
self.context!.beginPDFPage(pageInfo as CFDictionary)
drawReport()
self.context!.endPDFPage()
// Close the PDF context and write the contents out.
self.context!.closePDF()
self.context = nil
//DebugLog("generatePdfWithFilePath() completed")
}