objective-cmacoscgpdfdocumentcgpdf

Add text to PDF Page using CGPDFContext on OS X


I have tried to add text to an exist PDF file, which has 5 pages, by CGPDF and CGPDFContext but failed. I have set the font, DrawingMode, FillColor... Did I miss something in the code?

    CGContextRef writeContext = NULL;
    CGRect mediaBox;
    CGPDFPageRef page;
    size_t i;

        page = CGPDFDocumentGetPage(inputDoc, 1);
        mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);

        if (! writeContext)
            writeContext = CGPDFContextCreateWithURL(url, &mediaBox, NULL);





        CGPDFContextBeginPage(writeContext, NULL);
        CGContextDrawPDFPage(writeContext, page);

        //Add text

        CGContextSelectFont(writeContext, "Helvetic", 26, kCGEncodingMacRoman);
        CGContextSetTextDrawingMode(writeContext, kCGTextFill);
        CGContextSetRGBFillColor(writeContext, 0, 0, 0, 1);
        const char *text="Hello Text Test";
        CGContextShowTextAtPoint(writeContext, 100, 100, text, strlen(text));


        //=========

        CGPDFContextEndPage(writeContext);
    }

    if (writeContext)
    {
        CGPDFContextClose(writeContext);
        CGContextRelease(writeContext);
    }

Solution

  • I found you have a typo in font name Helvetica

    CGContextSelectFont(writeContext, "Helvetica", 26, kCGEncodingMacRoman);