Rendering a UIView into a PDF as vectors on an iPad - Sometimes renders as bitmap, sometimes as vectors

The only way I found to make it so labels are rendered vectorized is to use a subclass of UILabel with the following method:

/** Overriding this CALayer delegate method is the magic that allows us to draw a vector version of the label into the layer instead of the default unscalable ugly bitmap */
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    BOOL isPDF = !CGRectIsEmpty(UIGraphicsGetPDFContextBounds());
    if (!layer.shouldRasterize && isPDF)
        [self drawRect:self.bounds]; // draw unrasterized
    else
        [super drawLayer:layer inContext:ctx];
}

Swift 5.x:

override func draw(_ layer: CALayer, in ctx: CGContext) {
    let isPDF = !UIGraphicsGetPDFContextBounds().isEmpty

    if !self.layer.shouldRasterize && isPDF {
        self.draw(self.bounds)
    } else {
        super.draw(layer, in: ctx)
    }
}

That does the trick for me: labels are unrasterized and selectable in the resulting PDF view, and behave normally when rendered to the screen.

Tags:

Ios

Pdf

Uiview

Ipad