Портирование создания PDF-документа с iOS на Mac OS X - PullRequest
7 голосов
/ 13 августа 2011

Я портирую свой код с 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();

Ответы [ 2 ]

13 голосов
/ 13 августа 2011

Используйте CGPDFContextCreateWithURL вместо UIGraphicsBeginPDFContextToFile (параметры очень похожи). Чтобы начать / завершить страницы, используйте CGPDFContextBeginPage и CGPDFContextEndPage. Когда вы закончите, позвоните CGPDFContextClose вместо UIGraphicsEndPDFContext.

Остальное может остаться прежним - Core Graphics существует как на iOS, так и на Mac OS X - это также означает, что вы можете использовать функции, которые я упомянул выше, на iOS, если вы хотите использовать один и тот же код на обеих платформах .

0 голосов
/ 06 августа 2018

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")
    }
...