Search code examples
iospdfquartz-graphicsquartz-2d

drawInRect doesn't work with PDF


I am updating an old app but I am not able to make drawInRect working on PDF context.

I replaced the deprecated function CGContextShowTextAtPoint with CGContextShowTextAtPoint (see code below) but it doesn't write any text.

Where am I wrong?

This is my code:

-(NSMutableData *) writeToPDF {

CGRect          pageRect;

pageRect = CGRectMake(0.0f, 0.0f, 612, 850);

NSMutableData *pdfData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData);

CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &pageRect, NULL);

CGContextSetTextDrawingMode (pdfContext, kCGTextFill);

// Page 1

CGContextBeginPage(pdfContext, &pageRect);
CGContextSetRGBStrokeColor(pdfContext, 0, 0, 0, 1);

CGAffineTransform transf = CGAffineTransformMake(1, 0, 0, -1, 0, pageRect.size.height);
CGContextConcatCTM(pdfContext, transf);

// Line - OK

CGContextMoveToPoint(pdfContext,0,0);
CGContextAddLineToPoint(pdfContext,pageRect.size.width,pageRect.size.height);
CGContextDrawPath(pdfContext, kCGPathStroke);

CGContextSetTextDrawingMode (pdfContext, kCGTextFill);

CGAffineTransform myTextTransform = CGAffineTransformMake(1,0,0,-1,0,0);
CGContextSetTextMatrix(pdfContext, myTextTransform);

// Text - Old working code to replace because CGContextSelectFont and CGContextShowTextAtPoint are deprecated

CGContextSelectFont(pdfContext, "Helvetica", 20, kCGEncodingMacRoman);
CGContextShowTextAtPoint(pdfContext, 50, 50, [@"Hello" UTF8String], [@"Hello" length]);

// Text - Replacing code that doesn't work 

NSDictionary *attrs = @{ NSForegroundColorAttributeName : [UIColor blackColor],
                         NSFontAttributeName : [UIFont systemFontOfSize:20]
                       };


[@"Hello2" drawInRect:CGRectMake(50, 100, 100, 100) withAttributes:attrs];

CGContextDrawPath(pdfContext, kCGPathStroke);

CGContextEndPage(pdfContext);

//

CGPDFContextClose(pdfContext);
CGContextRelease(pdfContext);

CGDataConsumerRelease(dataConsumer);

return pdfData;
}

Solution

  • As opposed to the other functions you use, drawInRect doesn't take a graphics context. That means it uses the current graphics context and you have to make sure your PDF context is current before making the call.

    Making your graphics context current can be done with the UIGraphicsPushContext function. Just don't forget to pop the graphics context again once you're done with it.