Swift 图片转PDF文件

import UIKit
import Foundation

extension Array where Element == UIImage {
    
    func generatePDF(filePath: String, success: ()->(), failure: ()->()) {
        // 定义 A4 纸尺寸(单位:点,1 英寸 = 72 点)
        let a4Size = CGSize(width: 595.2, height: 841.8)
        // 定义页边距
        let margin: CGFloat = 10
        let contentSize = CGSize(width: a4Size.width - 2 * margin, height: a4Size.height - 2 * margin)
        
        // 开始 PDF 上下文
        UIGraphicsBeginPDFContextToFile(filePath, .zero, nil)
        
        for image in self {
            // 开始一个新的 PDF 页面
            UIGraphicsBeginPDFPageWithInfo(CGRect(origin: .zero, size: a4Size), nil)
            
            // 获取当前图形上下文
            guard let _ = UIGraphicsGetCurrentContext() else { continue }
            
            // 计算图片的缩放比例
            let imageSize = image.size
            let scaleWidth = contentSize.width / imageSize.width
            let scaleHeight = contentSize.height / imageSize.height
            let scale = Swift.min(scaleWidth, scaleHeight)
            
            // 计算图片的绘制尺寸
            let drawSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
            
            // 计算图片的绘制位置,使其居中
            let drawX = margin + (contentSize.width - drawSize.width) / 2
            let drawY = margin + (contentSize.height - drawSize.height) / 2
            let drawRect = CGRect(x: drawX, y: drawY, width: drawSize.width, height: drawSize.height)
            
            // 绘制图片
            image.draw(in: drawRect)
        }
        // 结束 PDF 上下文
        UIGraphicsEndPDFContext()
        
        if FileManager.default.fileExists(atPath: filePath) {
            success()
        } else {
            print("Failed to convert images to PDF.")
            failure()
        }
    }
}

使用:

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let filepath = documentsDirectory.appendingPathComponent("test.pdf").path

guard let image = UIImage(named: "your image") else { return }
let imageArray = [image]
imageArray.generatePDF(filePath: filePath) { [weak self] in
    guard let `self` = self else { return }
    
} failure: {
    
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容