Аннотирование PDF-файла и сохранение в Swift - PullRequest
0 голосов
/ 15 февраля 2020

В моем приложении iOS, использующем swift, я аннотировал поле pdf и сохранял в каталоге документов. Представление правильно отображает аннотированное поле, и файл сохраняется с аннотацией в каталоге документов, однако в области отладки я получаю сообщения. Последний метод для двух прогонов был Ok, но затем также выдавалось сообщение об ошибке, хотя отображаемый файл и сохраненный файл в каталоге do c были в порядке. Есть идеи?

2020-02-14 21:51:23.245079-0800 PDFSaving[4092:1084625] [Unknown process name] Failed to load /System/Library/PrivateFrameworks/CorePDF.framework/Versions/A/CorePDF


2020-02-14 21:51:23.262963-0800 PDFSaving[4092:1084625] Error: Attempting to save dictionary with key: <CGPDFNameRef (/Encoding)>. Dictionary keys must be of type string.


2020-02-14 21:51:23.263062-0800 PDFSaving[4092:1084625] Error: Attempting to save dictionary with key: <CGPDFNameRef (/Font)>. Dictionary keys must be of type string.


2020-02-14 21:51:23.263113-0800 PDFSaving[4092:1084625] Error: Could not create dictionary value for key: /DR. Invalid value.


2020-02-14 21:51:23.263161-0800 PDFSaving[4092:1084625] Error: Cannot save value for annotation key: /DR. Invalid type. 

Я использовал различные методы для сохранения файла PDF, но все они выдают одно и то же сообщение в области отладки`

// 1-й метод удаления и сохранения файла / / Сохранение файла с ошибками в области отладки

        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let fileNameWithPath = "\(path)/editedFile.pdf"

        if FileManager.default.fileExists(atPath: getFilePath()){
            do{
                try FileManager.default.removeItem(atPath: getFilePath())
                print("File path for deleted file: \(path)")
                print("File is deleted successfully, path & filename of deleted file: \(fileNameWithPath)")
            }catch{
                print("error while deleting item from docDir :: \(error.localizedDescription)")
            }
        }

        if let data = pdfDocument.dataRepresentation(){

            let url = URL(fileURLWithPath: fileNameWithPath)
            do{
               try data.write(to: url)

                print("pdf saved successfully \(fileNameWithPath)")
            }catch{
                print("error while saving file \(error.localizedDescription)")

                }
            }

// 2-й способ удаления и сохранения файла
// Сохранение файла с ошибками в области отладки

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let fileNameWithPath = "\(path)/editedFile.pdf"

if FileManager.default.fileExists(atPath: getFilePath()){
    do{
        try FileManager.default.removeItem(atPath: getFilePath())
        print("File path for deleted file: \(path)")
        print("File is deleted successfully, path & filename of deleted file: \(fileNameWithPath)")
    }catch{
        print("error while deleting item from docDir :: \(error.localizedDescription)")
    }
}

    guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
        let data = pdfView.document?.dataRepresentation() else {return}
    let fileURL = url.appendingPathComponent(filename)

    do {
        try data.write(to: fileURL)
        print("File path of saved file : \(path)")
        print("pdf saved successfully, path and filename of saved file: \(fileNameWithPath)")
    } catch {
        print("error while saving file \(error.localizedDescription)")
    }

// 3-й метод удаления и сохранения файла
// Пустой файл сохраняется без ошибок в области отладки

    let bundlePath = Bundle.main.path(forResource: "QW484A_2017R8", ofType: ".pdf")
    let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let fileManager = FileManager.default
    let fullDestPath = URL(fileURLWithPath: destPath).appendingPathComponent("editedFile.pdf")

    if fileManager.fileExists(atPath: fullDestPath.path){

               do {

                   try fileManager.removeItem(at: fullDestPath)
                   print("File path for removed file: \(destPath)")
                   print("File path & filename of file removed: \(fullDestPath)")
               }
                   catch{
                       print("error while removing modified file: \(error.localizedDescription)")
                   }
               }
    do{
        try fileManager.copyItem(atPath: bundlePath!, toPath: fullDestPath.path)
        print("File path of saved file : \(destPath)")
        print("database saved successfully, path and filename of saved file: \(fullDestPath.path)")

    }catch{
        print("error while saving modified file: \(error.localizedDescription)")
        }

// 4-й метод удаления и сохранения // Сохранение файла с ошибками в области отладки

    let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
    let fileManager = FileManager.default
    let fullDestPath = URL(fileURLWithPath: destPath).appendingPathComponent("editedFile.pdf")

    if fileManager.fileExists(atPath: fullDestPath.path){

               do {

                   try fileManager.removeItem(at: fullDestPath)
                   print("File path for removed file: \(destPath)")
                   print("File path & filename of file removed: \(fullDestPath)")
               }
                   catch{
                       print("error while removing modified file: \(error.localizedDescription)")
                   }
               }

    self.pdfDocument.write(to: fullDestPath)
    print("The save filed path and name: \(fullDestPath)")

// 5-й метод сохранения
// Сохранение файла с ошибками в области отладки

    guard let url2 = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first,
        let data = pdfView.document?.dataRepresentation() else {return}
    let fileURL = url2.appendingPathComponent("editedfile.pdf")



    do {
        try data.write(to: fileURL)
        print("print path: \(fileURL)")
    } catch {
        print(error.localizedDescription)
    }

// 6-й метод

let destPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
       let fileManager = FileManager.default
       let fullDestPath = URL(fileURLWithPath: destPath).appendingPathComponent("editedFile.pdf")

       if fileManager.fileExists(atPath: fullDestPath.path){

                  do {

                      try fileManager.removeItem(at: fullDestPath)
                      print("File path for removed file: \(destPath)")
                      print("File path & filename of file removed: \(fullDestPath)")
                  }
                      catch{
                          print("error while removing modified file: \(error.localizedDescription)")
                      }
                  }

        self.pdfView.document?.write(to: fullDestPath)

        print("The save filed path and name: \(fullDestPath)")

`

1 Ответ

0 голосов
/ 07 марта 2020

Итак, наконец, я обхожу эту проблему. Я думал обновить, так как это может повредить другим. Там было два метода, использованных для генерации PDF-формы, ist форма была создана в слове, а затем перенесена в PDF с аннотациями, во 2-м методе PDF-форма была создана с использованием Acro Form, оба представляли вышеуказанную проблему. В 3-й попытке я создал PDF-форму с помощью Adobe Acrobat D C с нуля и попытался, на этот раз без проблем сохранить PDF с аннотациями, похоже, это проблема преобразования формата

...