I have an iPad app and I'm trying to generate a PDF from a UIView and it's almost working perfectly.
The code is really simple as follows:
UIGraphicsBeginPDFContextToFile( filename, bounds, nil );
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[view.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
This works really well with one weird exception. If the view has been on screen before being rendered to PDF then the UILabels on the view are rendered to the PDF as wonderful vectors. If the view has not yet been on the screen (IE the controller was initWithNib etc but hasn't been pushed into a navigation controller or anything) then the text is rendered as a bitmap at 'ipad' resolution.
It's like the act of getting rendered to the screen sets up the view to be rendered as vectors when I subsequently render it to a pdf context.
Is there some method I can call or property I can set on the view or the layer or elsewhere to mimic this behaviour without having to show the view on screen?
Is it something to do with UIViewPrintFormatter?
What about if you add the view on screen but at offscreen coordinates. This seems more like a hack but it might work.
Use
drawInContext
rather thanrenderInContext
.Trying using the view's viewPrintFormatter.
Instead of
[view.layer renderInContext:pdfContext];
try this
I want to suggest an alternative to mprudhom's great solution: Using the
UIString
extensions you can also make the text in theUILabel
be rendered as font (with select'n'copy support etc.) This way the glyphs of the font are embedded in the PDF correctly.To support right and center text alignments as well as the default vertical centered alignment, I had to calculate a bounding box for the
drawInRect
method.The only way I found to make it so labels are rendered vectorized is to use a subclass of UILabel with the following method:
Swift 5.x:
That does the trick for me: labels are unrasterized and selectable in the resulting PDF view, and behave normally when rendered to the screen.