1

网址让我获取 pdf。我需要一个 4 页的 pdf 文件来获取 UIImage,但不是全部,而只是页面的一部分。请告诉我如何使这更容易。感谢您花费的时间示例

4

2 回答 2

5

Stefan Kieleithner 写了一篇名为Extracting Images from a PDF in Swift的博文,展示了如何从 PDF 页面中提取图像。以下代码是 Swift 5 / iOS 12 Playground 页面中呈现的代码的实现:

import Foundation
import PDFKit
import MobileCoreServices

func getEmbeddedImages(in pdfPage: PDFPage) -> [UIImage] {
    guard let cgPDFPage = pdfPage.pageRef, let dictionary = cgPDFPage.dictionary else {
        print("Couldn't open page.")
        return []
    }
    var res: CGPDFDictionaryRef?
    guard CGPDFDictionaryGetDictionary(dictionary, "Resources", &res), let resources = res else {
        print("Couldn't get Resources.")
        return []
    }
    var xObj: CGPDFDictionaryRef?
    guard CGPDFDictionaryGetDictionary(resources, "XObject", &xObj), let xObject = xObj else {
        print("Couldn't load page XObject.")
        return []
    }

    //Enumerate all of the keys in `dict', calling the block-function `block' once for each key/value pair.
    var imageKeys = [String]()
    CGPDFDictionaryApplyBlock(xObject, { key, object, _ in
        var stream: CGPDFStreamRef?
        guard CGPDFObjectGetValue(object, .stream, &stream),
            let objectStream = stream,
            let streamDictionary = CGPDFStreamGetDictionary(objectStream) else {
                return true
        }

        var subtype: UnsafePointer<Int8>?
        guard CGPDFDictionaryGetName(streamDictionary, "Subtype", &subtype), let subtypeName = subtype else {
            return true
        }

        if String(cString: subtypeName) == "Image" {
            imageKeys.append(String(cString: key))
        }
        return true
    }, nil)

    let allPageImages = imageKeys.compactMap { imageKey -> UIImage? in
        var stream: CGPDFStreamRef?
        guard CGPDFDictionaryGetStream(xObject, imageKey, &stream), let imageStream = stream else {
            print("Couldn't get image stream.")
            return nil
        }
        var format: CGPDFDataFormat = .raw
        guard let data = CGPDFStreamCopyData(imageStream, &format) else {
            print("Couldn't convert image stream to data.")
            return nil
        }
        guard let image = UIImage(data: data as Data) else {
            print("Couldn't convert image data to image.")
            return nil
        }
        return image
    }

    return allPageImages
}

用法:

let fileUrl = Bundle.main.url(forResource: "File", withExtension: "pdf")!
let pdfDocument = PDFDocument(url: fileUrl)!
let pdfPage = pdfDocument.page(at: 0)!
let images = getEmbeddedImages(in: pdfPage)
print(images)
于 2017-12-22T23:11:02.460 回答
1

使用此框架将 UIImage 转换为 PDF。

https://github.com/mindbrix/UIImage-PDF

于 2013-02-27T07:13:01.243 回答