ios - 如何将复杂的 UIView 渲染成高分辨率的 PDF 上下文?

标签 ios uiview pdf-generation

SO 上有几个问题询问如何将 UIView 渲染到 PDF 上下文中,但它们都使用 view.layer.renderInContext(pdfContext),这会导致 72 DPI 图像(打印时看起来很糟糕)。我正在寻找的是一种以某种方式让 UIView 以大约 300 DPI 的分辨率呈现的技术。

最佳答案

最后,我能够从之前的几篇帖子中得到提示并整理出一个解决方案。我发布这个是因为我花了很长时间才开始工作,我真的希望能节省其他人做同样事情的时间和精力。

此解决方案使用两种基本技术:

  1. 将 UIView 渲染到缩放位图上下文中以生成大图像
  2. 将图片绘制到缩小后的PDF Context中,使绘制的图片具有高分辨率

建立你的观点:

let v = UIView()
... // then add subviews, constraints, etc

创建 PDF 上下文:

UIGraphicsBeginPDFContextToData(data, docRect, stats.headerDict) // zero == (612 by 792 points)

defer { UIGraphicsEndPDFContext() }

UIGraphicsBeginPDFPage();

guard let pdfContext = UIGraphicsGetCurrentContext() else { return nil }

// I tried 300.0/72.0 but was not happy with the results
let rescale: CGFloat = 4 // 288 DPI rendering of VIew

// You need to change the scale factor on all subviews, not just the top view!
// This is a vital step, and there may be other types of views that need to be excluded

然后创建一个具有扩展比例的图像的大位图:

func scaler(v: UIView) {
   if !v.isKindOfClass(UIStackView.self) {
      v.contentScaleFactor = 8
   }
   for sv in v.subviews {
      scaler(sv)
   }
}
scaler(v)

// Create a large Image by rendering the scaled view
let bigSize = CGSize(width: v.frame.size.width*rescale, height: v.frame.size.height*rescale)
UIGraphicsBeginImageContextWithOptions(bigSize, true, 1)
let context = UIGraphicsGetCurrentContext()!

CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillRect(context, CGRect(origin: CGPoint(x: 0, y: 0), size: bigSize))

// Must increase the transform scale
CGContextScaleCTM(context, rescale, rescale)

v.layer.renderInContext(context)

let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

现在我们有一个大图像,每个点代表一个像素。 为了以高分辨率将其绘制到 PDF 中,我们需要在以大尺寸绘制图像时缩小 PDF:

CGContextSaveGState(pdfContext)
CGContextTranslateCTM(pdfContext, v.frame.origin.x, v.frame.origin.y) // where the view should be shown

CGContextScaleCTM(pdfContext, 1/rescale, 1/rescale)

let frame = CGRect(origin: CGPoint(x: 0, y: 0), size: bigSize)
image.drawInRect(frame)

CGContextRestoreGState(pdfContext)

... // Continue with adding other items

你可以看到,与绘制的“S”相比,包含在奶油色位图中的左侧“S”看起来相当不错,但属性字符串:

enter image description here

当通过 PDF 的简单呈现而不进行所有缩放来查看相同的 PDF 时,您将看到:

enter image description here

关于ios - 如何将复杂的 UIView 渲染成高分辨率的 PDF 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35442186/

相关文章:

ios - SwiftUI SceneDelegate 问题

ios - UITextField 点击检测

iphone - 查看未触发的加载方法

ios - UIView 子类没有接收到 touchesBegan、touchesEnded

coldfusion - Railo PDF 生成问题

ios - 我正在尝试使用圆角半径来查看放置在 UITableView 内的内容。这对我不起作用

ios - 什么是 'UIView-Encapsulated-Layout-Width' 约束?

ios - UIView 图层上的阴影

java - 使用 iText 从多个模板创建单个 PDF 文件

pdf - 使用 Ghostscript 替换 PDF 中的颜色