【问题标题】:Force PDF page to fill context强制 PDF 页面填充上下文
【发布时间】:2016-06-29 06:57:46
【问题描述】:

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

我设法创建了一个具有我想要的图像大小的上下文 (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 页面绘制以填充上下文大小的正确方法是什么?

【问题讨论】:

    标签: ios swift pdf core-graphics


    【解决方案1】:

    这是我想出的解决方案。

    据我所知,这适用于任何 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
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 2014-02-13
      • 2021-04-27
      • 2019-06-28
      • 2013-01-22
      • 1970-01-01
      相关资源
      最近更新 更多