12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- //
- // PDFConvertObject.swift
- // PDF Reader Pro
- //
- // Created by liujiajie on 2023/11/17.
- //
- import Foundation
- @objc(PDFConvertObjectDelegate)
- protocol PDFConvertObjectDelegate: AnyObject {
- @objc optional func PDFConvertObjectDidStartConversion(_ converter: PDFConvertObject, error: Error?)
- @objc optional func PDFConvertObjectDidEndConversion(_ converter: PDFConvertObject, error: Error?)
- @objc optional func PDFConvertObjectDidPdfPage(_ converter: PDFConvertObject, didPDFPageIndexA: Int, didPageCountA: Int)
- }
- class PDFConvertObject: NSObject {
- var delegate: PDFConvertObjectDelegate?
- var document: CPDFDocument?
- lazy var suffix: Int = {
- if suffix == 0 {
- var suf = self.document?.pageCount
- while suf ?? 0 > 10 {
- suf! /= 10
- suffix += 1
- }
- suffix += 1
- }
- return suffix
- }()
-
- override init() {
- super.init()
- suffix = 0
- }
-
- func stopConversionIfNeeded() {
- self.document?.cancelExtractImage()
- }
- func extractResourcesFromPDF(at pdfPathA: String, pdfPassword pdfPasswordA: String?, selectIndexSet indexSet: IndexSet, destDocPath destDocPathA: String, moreOptions moreOptionsA: [AnyHashable: Any]?) {
- self.document = CPDFDocument(url: URL(fileURLWithPath: pdfPathA))
- if pdfPasswordA?.count ?? 0 > 0 {
- self.document?.unlock(withPassword: pdfPasswordA)
- }
- self.document?.extractImage(fromPages: indexSet, toPath: destDocPathA) { (pageIndex, imageIndex, index) -> String? in
- let fileName = self.document?.documentURL.deletingPathExtension().lastPathComponent
- let imageName = String(format: "%@_Page%ld_%@", fileName ?? "",pageIndex+1,self.imageNumberSuffix(imageIndex+1))
- return imageName
- }
-
- self.delegate?.PDFConvertObjectDidEndConversion?(self, error: nil)
- }
- func imageNumberSuffix(_ imageIndex: Int) -> String {
- let indexString = String(format: "%d", imageIndex)
- var suffixString = ""
- if suffix > indexString.count {
- for _ in 0..<(suffix - indexString.count) {
- suffixString = "(suffixString)0"
- }
- suffixString = "(suffixString)(indexString)"
- return suffixString
- }
- suffixString = indexString
- return suffixString
- }
- }
|