ios - 强制 PDF 页面填充上下文

标签 ios swift pdf core-graphics

在我的项目中,我确实需要生成使用 CoreGraphics 生成的 PDF 页面的图像。

我成功创建了一个上下文,其中包含我想要的图像大小 (destinationSize: CGSize),但是当我使用 CGPDFPageGetDrawingTransform 函数时,它仅调整页面大小向下,但它不会缩放上下文以使页面填充目标矩形。

这是我项目中现在的代码摘录:

UIGraphicsBeginImageContextWithOptions(destinationSize, true, 0)

defer {
    UIGraphicsEndImageContext()
}

// Invert y axis (CoreGraphics and UIKit axes are differents)
CGContextTranslateCTM( ctx, 0, destinationSize.height);
CGContextScaleCTM(ctx, 1, -1)

let transform = CGPDFPageGetDrawingTransform(pageRef, .CropBox, CGRect(origin: CGPointZero, size: destinationSize), 0, true)
CGContextConcatCTM(ctx, transform)

// TODO We need force the page to fill all the dest rect when it's bigger than the CropBox size

CGContextDrawPDFPage(ctx, pageRef)

我尝试用这个缩放因子来缩放我的上下文,替换 TODO :

let contextScale: CGFloat = (pageRect.width < expectedWidth) ? expectedWidth / pageRect.width : 1
CGContextScaleCTM(ctx, contextScale, contextScale)

但它创建了一个不正确的绘图偏移,我对 CoreGraphics 转换有点迷失了。

重新缩放上下文以确保 pdf 页面绘制以填充上下文大小的正确方法是什么?

最佳答案

这是我想出的解决方案。

据我所知,这适用于任何 pdf 文档页面。 (经过多次旋转、裁剪框大小和原点测试。

func transformationForPage(_ pageNumber: Int, targetSize: CGSize) -> CGAffineTransform {
    let pageRef = getPage(pageNumber)
    let rotation = getPageRotationInteger(pageNumber)
    let cropbox = cropboxForPage(pageNumber)

    var transform = pageRef!.getDrawingTransform(.cropBox, rect: CGRect(origin: CGPoint.zero, size: targetSize), rotate: 0, preserveAspectRatio: true)

    // We change the context scale to fill completely the destination size
    if cropbox.width < targetSize.width {
        let contextScale = targetSize.width / cropbox.width
        transform = transform.scaledBy(x: contextScale, y: contextScale)

        transform.tx = -(cropbox.origin.x * transform.a + cropbox.origin.y * transform.b)
        transform.ty = -(cropbox.origin.x * transform.c + cropbox.origin.y * transform.d)

        // Rotation handling
        if rotation == 180 || rotation == 270 {
            transform.tx += targetSize.width
        }
        if rotation == 90 || rotation == 180 {
            transform.ty += targetSize.height
        }
    }

    return transform
}

关于ios - 强制 PDF 页面填充上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35984129/

相关文章:

c# - 在 C# 中使用 iTextSharp 阅读 pdf 内容

iOS tableview 在将图像加载到 imageview 时滞后于滚动

具有多个离线 map 的 iOS 导航应用程序 : which library to use?

android - 使用 gem fcm 在 IOS 中接收推送通知

ios - 在 iOS 上上传个人资料图片时打开 Facebook 应用

ios - 在 Swift 中的 View Controller 之间传递数据

ios - MPMusicPlayer 设置

c - (Enum) -1 在 C 中代表什么值?如何在 Swift 中编写它?

android - 如何在使用 pdf(Android) 加载 url 的 Web View 上启用捏合缩放?

用于插入的 pdftk 字段名称