Oh well. Here's a simple way to render a UITextView as real text into a PDF using TextKit 2. It currently supports only one text attachment per paragraph, because you apparently can't use fragment.draw(at:origin:) to display attachments.
let renderer = UIGraphicsPDFRenderer(bounds: pageRect, format: format)
let data = renderer.pdfData { (context) in
let cgContext = context.cgContext
textView.textLayoutManager.enumerateTextLayoutFragments(from: location, options: [.ensuresLayout, .estimatesSize, .ensuresExtraLineFragment], using: { fragment in
let frame = fragment.layoutFragmentFrame
let origin = page.textView?.frame.origin ?? CGPointZero
var actualFrame = frame
actualFrame.origin.x += origin.x
actualFrame.origin.y += origin.y
if let provider = fragment.textAttachmentViewProviders.first, let view = provider.view {
// Draw a text attachment
let attachmentFrame = fragment.frameForTextAttachment(at: fragment.rangeInElement.location)
actualFrame.origin.y += attachmentFrame.origin.y
cgContext.saveGState()
cgContext.translateBy(x: actualFrame.origin.x, y: actualFrame.origin.y)
view.layer.render(in: cgContext)
cgContext.restoreGState()
return true
} else {
// Draw a normal paragraph
fragment.draw(at: origin, in: cgContext)
}
return true
})
}
I have no idea why Apple decided make this the default behavior in UITextView, I doubt most people would want their text views to be rasterized in PDFs.