gpt4 book ai didi

swift - 在PDF中绘制NSString(水印)

转载 作者:行者123 更新时间:2023-11-30 11:21:05 24 4
gpt4 key购买 nike

这个问题我已经发了很多次了,但还是找不到正确的答案。我的目标是加载 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
}

最佳答案

您在项目中使用 PDFKit 吗?如果是,请下载Apple的示例代码here 。并替换行:

let string: NSString = "U s e r   3 1 4 1 5 9" 

用这一行:

let string: NSString = NSString(format: "Page %@", "\(self.pageRef?.pageNumber ?? 0)")

关于swift - 在PDF中绘制NSString(水印),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51261699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com