这个问题我已经贴了很多次了,但我仍然找不到正确的答案。我的目标是加载一个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
}发布于 2018-11-01 14:03:59
你在你的项目中使用PDFKit吗?如果是,请下载苹果的示例代码here。并替换行:
let string: NSString = "U s e r 3 1 4 1 5 9" 使用这一行:
let string: NSString = NSString(format: "Page %@", "\(self.pageRef?.pageNumber ?? 0)")https://stackoverflow.com/questions/51261699
复制相似问题