iOS Development

ios – Avoiding rasterizing UITextView when exporting to PDF

Spread the love

I am attempting to render a UIView to PDF, whereas sustaining textual content components as precise textual content and never rasterizing them.

I am utilizing TextKit 2 backed UITextView and NSTextLayoutManager to supply the contents. Nonetheless, it doesn’t matter what I do, UITextView will get rasterized right into a bitmap.

Here is the fundamental code:

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

let information = renderer.pdfData { (context) in
    for web page in self.pageViews {
        let cgContext = context.cgContext               
        web page.layer.render(in: cgContext)

A web page view often comprises one UITextView, which makes use of considerably superior structure, so sadly I am unable to simply toss it right into a single NSAttributedString and draw right into a CoreText context.

There’s a hack to get UILabels to render themselves as non-rasterized textual content, and if I perceive appropriately, it really works by simply really drawing them on the present context.

Curiously, when offering UILabel view through NSTextAttachmentViewProvider to a textual content view utilizing TextKit 2, the UILabels inside a textual content view will not get rasterized:

labels are not rasterized

This hinted that the precise textual content fragments are those that get rasterized when drawing, not the entire view, and I used to be proper. You may enumerate the textual content fragments and draw them instantly on the context, which makes them stay as textual content quite than turn out to be a bitmap:

web page.textView?.textLayoutManager?.enumerateTextLayoutFragments(from: location, choices: [.ensuresLayout, .estimatesSize, .ensuresExtraLineFragment], utilizing: { fragment in
    let body = fragment.layoutFragmentFrame
    fragment.draw(at: body.origin, in: cgContext)
    return true

Nonetheless, this causes different points, as a result of structure coordinates will likely be all over and never confined to the textual content view itself (and much more so for my customized NSTextLayoutFragment class), and textual content attachments will not get drawn this fashion both, however show a skewed placeholder icon.

I am questioning if there’s a method to make UITextView and NSTextLayoutManager to attract their contents much like UILabel, so the fragments would stay as textual content within the PDF, quite than turn out to be a bitmap?

One thought on “ios – Avoiding rasterizing UITextView when exporting to PDF

  1. I do not even know how I ended up here but I thought this post was great I dont know who you are but definitely youre going to a famous blogger if you arent already Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *