PDFKit中如何计算PDFPage大小? 如何计算如何获取精确 10 x 10 厘米大小的页面

问题描述

我在代码中所做的就是迭代我的图像集中的每个图像:

        print(UIScreen.main.scale) //3.0
        print(UIScreen.main.nativeScale) //3.0
        for card in Box.sortedCards {
            if let image = card.image?.scaledWithMaxWidthOrHeightValue(value: 300) {
                print(image.size.width) //300
                print(image.size.height) //300
                if let page = pdfpage(image: image) {
                    document.insert(page,at: document.pageCount)
                }
            }
        }

但是,一旦我使用 UIActivityViewController 预览我的 PDFDocument,然后将其共享到我的 macbook,我会得到以下结果:

enter image description here

如何计算?

通过 UIActivityViewController 共享到我的 Mac 的每个图像都包含以下信息:

enter image description here

我需要什么?

我需要计算图像大小,以在 10 厘米上每页精确 10 厘米预览 PDFDocument,无论将使用什么 ios 设备。

解决方法

如何计算

图像的物理尺寸(以像素为单位)等于图像的逻辑尺寸乘以图像的比例因子。

Image Size (pixels) = UIImage.size * UIImage.scale

如果比例因子为 1,则图像的 DPI 为每英寸 72 像素。

Image DPI (pixels/inch) = UIImage.scale * 72.0

获取页面大小:

Page Size (inches) = Image Size / Image DPI

如何获取精确 10 x 10 厘米大小的页面

我不确定您的 scaledWithMaxWidthOrHeightValue 是如何实现的。为了说明计算,我假设您已经有一个 UIImage 实例,其尺寸为 size 300x300。

print(UIScreen.main.scale) //3.0
print(UIScreen.main.nativeScale) //3.0
for card in box.sortedCards {
    if let image = card.image?.scaledWithMaxWidthOrHeightValue(value: 300) {
        print(image.size.width) //300
        print(image.size.height) //300
        let defaultDPI = 72.0
        let centimetersPerInch = 2.54
        let expectedPageSize = 10.0 // centimeters
        var scale = 300.0 / defaultDPI * centimetersPerInch / expectedPageSize * image.scale.native
        scale += 0.001 // work around accuracy to get exact 10 centimeters
        if let cgImage = image.cgImage {
            let scaledImage: UIImage = UIImage(cgImage: cgImage,scale: CGFloat(scale),orientation: image.imageOrientation)
            if let page = PDFPage(image: scaledImage) {
                document.insert(page,at: document.pageCount)
            }
        }
    }
}