KMConvertPDFManager.swift 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // KMConvertPDFManager.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2022/12/19.
  6. //
  7. import Cocoa
  8. class KMConvertPDFPage: CPDFPage {
  9. var url: URL?
  10. override func draw(with box: CPDFDisplayBox, to context: CGContext!) {
  11. super.draw(with: box, to: context)
  12. if (context != nil) {
  13. NSGraphicsContext.current = NSGraphicsContext.init(cgContext: context, flipped: false)
  14. }
  15. drawImageTocontext(context)
  16. }
  17. func drawImageTocontext(_ context: CGContext) -> Void {
  18. let blankA4Size = CGSize(width: 595, height: 842)
  19. let imageCIImage = CIImage(data: try! Data(contentsOf: url!))
  20. let imagesize = imageCIImage?.extent.size
  21. var rect = NSZeroRect
  22. let image = NSImage.init(contentsOfFile: url!.path)
  23. if imagesize!.width <= blankA4Size.width && imagesize!.height <= blankA4Size.height {
  24. rect = CGRect(x: (blankA4Size.width-imagesize!.width)/2, y: (blankA4Size.height-imagesize!.height)/2, width: imagesize!.width, height: imagesize!.height)
  25. } else {
  26. let scanl = min(blankA4Size.width/imagesize!.width, blankA4Size.height/imagesize!.height)
  27. rect = CGRect(x: 0, y: 0, width: imagesize!.width * scanl, height: imagesize!.height * scanl)
  28. }
  29. image?.draw(in: rect, from: NSZeroRect, operation: .sourceOver, fraction: 1.0)
  30. }
  31. }
  32. class KMConvertPDFManager: NSObject {
  33. class func convertImages(_ imagesPaths: [URL], savePath: String, completionHandler complet: @escaping (_ success: Bool, _ errorDic: [String: Any]) -> Void) -> Void {
  34. DispatchQueue.global().async {
  35. let pdf = CPDFDocument.init()
  36. let blankA4Size = CGSize(width: 595, height: 842)
  37. for url in imagesPaths {
  38. let page = KMConvertPDFPage.init()
  39. page.url = url
  40. let imageCIImage = CIImage(data: try! Data(contentsOf: url))
  41. let size = imageCIImage?.extent.size
  42. var contextSize = NSZeroSize
  43. if size!.width <= blankA4Size.width && size!.height <= blankA4Size.height {
  44. contextSize = blankA4Size
  45. } else {
  46. let scanl = min(blankA4Size.width/size!.width, blankA4Size.height/size!.height)
  47. contextSize = CGSize(width: size!.width * scanl, height: size!.height * scanl)
  48. }
  49. page.setBounds(CGRect(x: 0, y: 0, width: contextSize.width, height: contextSize.height), for: .mediaBox)
  50. pdf?.insertPageObject(page, at: pdf!.pageCount)
  51. }
  52. DispatchQueue.main.async {
  53. let isSucceed = pdf?.write(toFile: savePath)
  54. complet(isSucceed!, [:])
  55. }
  56. }
  57. }
  58. }