PDFConvertObject.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // PDFConvertObject.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by liujiajie on 2023/11/17.
  6. //
  7. import Foundation
  8. @objc(PDFConvertObjectDelegate)
  9. protocol PDFConvertObjectDelegate: AnyObject {
  10. @objc optional func PDFConvertObjectDidStartConversion(_ converter: PDFConvertObject, error: Error?)
  11. @objc optional func PDFConvertObjectDidEndConversion(_ converter: PDFConvertObject, error: Error?)
  12. @objc optional func PDFConvertObjectDidPdfPage(_ converter: PDFConvertObject, didPDFPageIndexA: Int, didPageCountA: Int)
  13. }
  14. class PDFConvertObject: NSObject {
  15. var delegate: PDFConvertObjectDelegate?
  16. var document: CPDFDocument?
  17. lazy var suffix: Int = {
  18. if suffix == 0 {
  19. var suf = self.document?.pageCount
  20. while suf ?? 0 > 10 {
  21. suf! /= 10
  22. suffix += 1
  23. }
  24. suffix += 1
  25. }
  26. return suffix
  27. }()
  28. override init() {
  29. super.init()
  30. suffix = 0
  31. }
  32. func stopConversionIfNeeded() {
  33. self.document?.cancelExtractImage()
  34. }
  35. func extractResourcesFromPDF(at pdfPathA: String, pdfPassword pdfPasswordA: String?, selectIndexSet indexSet: IndexSet, destDocPath destDocPathA: String, moreOptions moreOptionsA: [AnyHashable: Any]?) {
  36. self.document = CPDFDocument(url: URL(fileURLWithPath: pdfPathA))
  37. if pdfPasswordA?.count ?? 0 > 0 {
  38. self.document?.unlock(withPassword: pdfPasswordA)
  39. }
  40. self.document?.extractImage(fromPages: indexSet, toPath: destDocPathA) { (pageIndex, imageIndex, index) -> String? in
  41. let fileName = self.document?.documentURL.deletingPathExtension().lastPathComponent
  42. let imageName = String(format: "%@_Page%ld_%@", fileName ?? "",pageIndex+1,self.imageNumberSuffix(imageIndex+1))
  43. return imageName
  44. }
  45. self.delegate?.PDFConvertObjectDidEndConversion?(self, error: nil)
  46. }
  47. func imageNumberSuffix(_ imageIndex: Int) -> String {
  48. let indexString = String(format: "%d", imageIndex)
  49. var suffixString = ""
  50. if suffix > indexString.count {
  51. for _ in 0..<(suffix - indexString.count) {
  52. suffixString = "(suffixString)0"
  53. }
  54. suffixString = "(suffixString)(indexString)"
  55. return suffixString
  56. }
  57. suffixString = indexString
  58. return suffixString
  59. }
  60. }