1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- //
- // KMConvertPDFManager.swift
- // PDF Master
- //
- // Created by wanjun on 2022/12/19.
- //
- import Cocoa
- class KMConvertPDFPage: CPDFPage {
- var url: URL?
-
- override func draw(with box: CPDFDisplayBox, to context: CGContext!) {
- super.draw(with: box, to: context)
- if (context != nil) {
- NSGraphicsContext.current = NSGraphicsContext.init(cgContext: context, flipped: false)
- }
- drawImageTocontext(context)
- }
-
- func drawImageTocontext(_ context: CGContext) -> Void {
- let blankA4Size = CGSize(width: 595, height: 842)
- let imageCIImage = CIImage(data: try! Data(contentsOf: url!))
- let imagesize = imageCIImage?.extent.size
- var rect = NSZeroRect
- let image = NSImage.init(contentsOfFile: url!.path)
- if imagesize!.width <= blankA4Size.width && imagesize!.height <= blankA4Size.height {
- rect = CGRect(x: (blankA4Size.width-imagesize!.width)/2, y: (blankA4Size.height-imagesize!.height)/2, width: imagesize!.width, height: imagesize!.height)
- } else {
- let scanl = min(blankA4Size.width/imagesize!.width, blankA4Size.height/imagesize!.height)
- rect = CGRect(x: 0, y: 0, width: imagesize!.width * scanl, height: imagesize!.height * scanl)
- }
- image?.draw(in: rect, from: NSZeroRect, operation: .sourceOver, fraction: 1.0)
- }
- }
- class KMConvertPDFManager: NSObject {
-
- class func convertImages(_ imagesPaths: [URL], savePath: String, completionHandler complet: @escaping (_ success: Bool, _ errorDic: [String: Any]) -> Void) -> Void {
- DispatchQueue.global().async {
- let pdf = CPDFDocument.init()
- let blankA4Size = CGSize(width: 595, height: 842)
- for url in imagesPaths {
- let page = KMConvertPDFPage.init()
- page.url = url
- let imageCIImage = CIImage(data: try! Data(contentsOf: url))
- let size = imageCIImage?.extent.size
- var contextSize = NSZeroSize
-
- if size!.width <= blankA4Size.width && size!.height <= blankA4Size.height {
- contextSize = blankA4Size
- } else {
- let scanl = min(blankA4Size.width/size!.width, blankA4Size.height/size!.height)
- contextSize = CGSize(width: size!.width * scanl, height: size!.height * scanl)
- }
-
- page.setBounds(CGRect(x: 0, y: 0, width: contextSize.width, height: contextSize.height), for: .mediaBox)
- pdf?.insertPageObject(page, at: pdf!.pageCount)
- }
-
- DispatchQueue.main.async {
- let isSucceed = pdf?.write(toFile: savePath)
- complet(isSucceed!, [:])
- }
- }
- }
- }
|