I am making an attempt to render a UIView
to PDF, whereas sustaining textual content parts as precise textual content and never rasterizing them.
I am utilizing TextKit 2 backed UITextView
and NSTextLayoutManager
to offer the contents. Nevertheless, 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 {
context.beginPage()
let cgContext = context.cgContext
web page.layer.render(in: cgContext)
}
}
A web page view normally accommodates 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 UILabel
s 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.
Apparently, when offering UILabel
view by way of NSTextAttachmentViewProvider
to a textual content view utilizing TextKit 2, the UILabel
s inside a textual content view will not get 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 straight 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
})
Nevertheless, this causes different points, as a result of structure coordinates will probably be everywhere 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 strategy 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?