在PDF中绘制NSString(水印)

时间:2018-07-10 09:28:24

标签: swift image pdf nsstring draw

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

1 个答案:

答案 0 :(得分:0)

您在项目中使用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)")