如何有效地将PDF转换为PNG?

Mik*_*son 2 pdf macos swift

我有以下功能将PDF转换为一系列图像(每页一个图像):

import Quartz

func convertPDF(at sourceURL: URL, to destinationURL: URL, fileType: NSBitmapImageFileType, dpi: CGFloat = 200) throws -> [URL] {
    let fileExtension: String
    switch fileType {
    case .BMP:              fileExtension = "bmp"
    case .GIF:              fileExtension = "gif"
    case .JPEG, .JPEG2000:  fileExtension = "jpeg"
    case .PNG:              fileExtension = "png"
    case .TIFF:             fileExtension = "tiff"
    }

    let data = try Data(contentsOf: sourceURL)
    let pdfImageRep = NSPDFImageRep(data: data)!
    var imageURLs = [URL]()

    for i in 0..<pdfImageRep.pageCount {
        pdfImageRep.currentPage = i

        let width = pdfImageRep.size.width / 72 * dpi
        let height = pdfImageRep.size.height / 72 * dpi
        let image = NSImage(size: CGSize(width: width, height: height), flipped: false) { dstRect in
            pdfImageRep.draw(in: dstRect)
        }

        let bitmapImageRep = NSBitmapImageRep(data: image.tiffRepresentation!)!
        let bitmapData = bitmapImageRep.representation(using: fileType, properties: [:])!

        let imageURL = destinationURL.appendingPathComponent("\(sourceURL.deletingPathExtension().lastPathComponent)-Page\(i+1).\(fileExtension)")
        try bitmapData.write(to: imageURL, options: [.atomic])
        imageURLs.append(imageURL)
    }

    return imageURLs
}
Run Code Online (Sandbox Code Playgroud)

这种方法很好,性能不是很快,但并不重要.我的问题与内存消耗有关.假设我正在转换一个长PDF(Apple的10-Q,51页长):

let sourceURL = URL(string: "http://files.shareholder.com/downloads/AAPL/4907179320x0x952191/4B5199AE-34E7-47D7-8502-CF30488B3B05/10-Q_Q3_2017_As-Filed_.pdf")!
let destinationURL = URL(fileURLWithPath: "/Users/mike/PDF")
let _ = try convertPDF(at: sourceURL, to: destinationURL, fileType: .PNG, dpi: 200)
Run Code Online (Sandbox Code Playgroud)

在最后一页的末尾,内存使用量持续增加到~11GB!

我还注意到的一些事情:

  • 当我通过仪器运行时,它出人意料地显示没有泄漏.两个大记忆猪是bitmapImageRepbitmapData.它们似乎没有在迭代之间释放.
  • 即使与Debug构建相比,分析也会降低性能.
  • 减少DPI显然会减少内存占用,但行为仍然相同.内存随页数线性增加.
  • 无论是转换单页51页PDF还是51页单页PDF都是一样的.

那么我该如何减少内存占用?有没有更好的方法将PDF转换为图像?

Mik*_*son 7

经过一整天的努力,我最终回答了自己的问题.

解决方案是降低Core Graphics和Image I/O框架,将每个PDF页面呈现为位图上下文.这个问题非常适合于并行化,因为每个页面都可以在自己的线程上转换成位图.

struct ImageFileType {
    var uti: CFString
    var fileExtention: String

    // This list can include anything returned by CGImageDestinationCopyTypeIdentifiers()
    // I'm including only the popular formats here
    static let bmp = ImageFileType(uti: kUTTypeBMP, fileExtention: "bmp")
    static let gif = ImageFileType(uti: kUTTypeGIF, fileExtention: "gif")
    static let jpg = ImageFileType(uti: kUTTypeJPEG, fileExtention: "jpg")
    static let png = ImageFileType(uti: kUTTypePNG, fileExtention: "png")
    static let tiff = ImageFileType(uti: kUTTypeTIFF, fileExtention: "tiff")
}

func convertPDF(at sourceURL: URL, to destinationURL: URL, fileType: ImageFileType, dpi: CGFloat = 200) throws -> [URL] {
    let pdfDocument = CGPDFDocument(sourceURL as CFURL)!
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGImageAlphaInfo.noneSkipLast.rawValue

    var urls = [URL](repeating: URL(fileURLWithPath : "/"), count: pdfDocument.numberOfPages)
    DispatchQueue.concurrentPerform(iterations: pdfDocument.numberOfPages) { i in
        // Page number starts at 1, not 0
        let pdfPage = pdfDocument.page(at: i + 1)!

        let mediaBoxRect = pdfPage.getBoxRect(.mediaBox)
        let scale = dpi / 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.setFillColor(.white)
        context.fill(CGRect(x: 0, y: 0, width: width, height: height))
        context.scaleBy(x: scale, y: scale)
        context.drawPDFPage(pdfPage)

        let image = context.makeImage()!
        let imageName = sourceURL.deletingPathExtension().lastPathComponent
        let imageURL = destinationURL.appendingPathComponent("\(imageName)-Page\(i+1).\(fileType.fileExtention)")

        let imageDestination = CGImageDestinationCreateWithURL(imageURL as CFURL, fileType.uti, 1, nil)!
        CGImageDestinationAddImage(imageDestination, image, nil)
        CGImageDestinationFinalize(imageDestination)

        urls[i] = imageURL
    }
    return urls
}
Run Code Online (Sandbox Code Playgroud)

用法:

let sourceURL = URL(string: "http://files.shareholder.com/downloads/AAPL/4907179320x0x952191/4B5199AE-34E7-47D7-8502-CF30488B3B05/10-Q_Q3_2017_As-Filed_.pdf")!
let destinationURL = URL(fileURLWithPath: "/Users/mike/PDF")
let urls = try convertPDF(at: sourceURL, to: destinationURL, fileType: .png, dpi: 200)
Run Code Online (Sandbox Code Playgroud)

现在转换速度非常快.内存使用率要低得多.显然,DPI越高,它所需的CPU和内存就越多.不确定GPU加速,因为我只有一个弱的Intel集成GPU.