ios – Avoiding rasterizing UITextView when exporting to PDF


I’m trying to render a UIView to PDF, while maintaining text elements as actual text and not rasterizing them.

I’m using TextKit 2 backed UITextView and NSTextLayoutManager to provide the contents. However, no matter what I do, UITextView gets rasterized into a bitmap.

Here’s the basic code:

let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)

let data = renderer.pdfData { (context) in
    for page in self.pageViews {
        context.beginPage()
        let cgContext = context.cgContext               
        page.layer.render(in: cgContext)
    }
}

A page view usually contains one UITextView, which uses somewhat advanced layout, so unfortunately I can’t just toss it into a single NSAttributedString and draw into a CoreText context.

There’s a hack to get UILabels to render themselves as non-rasterized text, and if I understand correctly, it works by just actually drawing them on the current context.

Interestingly, when providing UILabel view via NSTextAttachmentViewProvider to a text view using TextKit 2, the UILabels inside a text view won’t get rasterized:

labels are not rasterized

This hints to that the actual text fragments are the ones that get rasterized when drawing, not the whole view. A related thread discusses how in some cases UITextView is not rasterized, but I haven’t been able to reproduce either behavior, which might be because of TextKit 2.

I’m wondering if there is a way to make UITextView and NSTextLayoutManager to draw their contents similar to UILabel, so the fragments would remain as text in the PDF, rather than bitmap?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img