【发布时间】:2018-07-10 09:28:24
【问题描述】:
这个问题我已经发过很多次了,但我还是找不到正确的答案。我的目标是加载 PDF(扫描的问卷页面),用页码标记每一页,并将每一页保存在单独的 JPEG 文件中以备后用。除了未绘制 NSString 之外,一切正常。当我从位图表示创建 NSGraphicsContext 但图像分辨率太低时,我工作得很好。所以,我断定这是一个 PDF 问题,但无法弄清楚它是什么。
let PDFAsData = try Data(contentsOf: pathname)
let dataInPDF = NSPDFImageRep(data: PDFAsData)!
let numberOfPages = dataInPDF.pageCount
for i in 0..<numberOfPages {
let pdfPage=pdfDocument.page(at: i+1)!
let mediaBoxRect = pdfPage.getBoxRect(.mediaBox)
let scale:CGFloat = 200.0/72.0
let width = Int(mediaBoxRect.width * scale)
let height = Int(mediaBoxRect.height * scale)
let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo)!
context.interpolationQuality = .high
context.scaleBy(x: scale, y: scale)
context.drawPDFPage(pdfPage)
context.saveGState()
do {
let paragraphStyle = NSMutableParagraphStyle.default().mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.alignment = NSTextAlignment.left
let textFontAttributes = [NSFontAttributeName: NSFont(name: "Arial Bold", size: 10.0)!,
NSForegroundColorAttributeName: NSColor.black,
NSParagraphStyleAttributeName: paragraphStyle]
let text = "\(fileNameNSString), page: \(i+1)" as NSString
text.draw(at: CGPoint(x:10, y:10), withAttributes: textFontAttributes)
}
context.flush()
context.restoreGState()
let image=context.makeImage()! // Creates and returns a CGImage to be saved as JPEG
}
【问题讨论】:
-
我使用 CATextLayer 找到了部分解决方案,但我还不能更改字符串在页面上的位置... let textLayer = CATextLayer() textLayer.string = "(fileNameNSString), page: ( i+1)" textLayer.font = "Arial Bold" 作为 CFTypeRef? textLayer.fontSize = 10.0 textLayer.foregroundColor = CGColor.black textLayer.alignmentMode = kCAAlignmentLeft textLayer.frame = CGRect(x: 0, y: 0, width: 500, height: 50) textLayer.draw(in: context) let image= context.makeImage()!
标签: swift image pdf nsstring draw