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

前端 未结 5 1973
眼角桃花
眼角桃花 2020-12-13 14:41

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:



        
5条回答
  •  借酒劲吻你
    2020-12-13 14:55

    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.

提交回复
热议问题