使用 Swift 5 - PDFKit 在 iOS 中编辑和保存现有的 pdf 文档



我一直在尝试编辑现有的pdf文件并将其保存到设备。我尝试将编辑后的文件保存到与未编辑文件相同的位置。但是无法保存该文件。相反,我遇到了这样的错误

  • 尝试使用键保存字典:。字典键的类型必须是字符串。
  • 无法为键/DR 创建字典值。值无效。
  • 无法保存注释键的值:/DR。 类型无效。
  • 尝试使用键保存字典:。字典键的类型必须是字符串。

这是我的代码:

pdfView.document?.write(to: pdfView.document!.documentURL!)

如何使用PDFKit将编辑的更改保存在pdf文件中?

以下是保存 PDF 的代码:

pdfView.document?.write(toFile: "Path To Save the File.")

如果仍然无法保存更改,请重新检查保存 pdf 的路径。

我认为,在同一个文件夹中,您不能创建两个同名的文件。

在这种情况下,这是因为旧文件正在被新文件替换。

我想通了这一点,我的 PDF 表单也有类似的问题。该表单最初是在 word 中创建的,并转换为 PDF 表单。 当我从头开始使用Adobe Acrobat DC创建PDF表单时,它正确地注释了PDF视图保存中的PDF,而没有上述问题

试试这个,可能会解决你的问题

if let data = pdfDocument?.dataRepresentation(){

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0] // Get documents folder
let folderPathUrl = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("samplePdf.pdf")
if FileManager.default.fileExists(atPath: folderPathUrl.path){
try? FileManager.default.removeItem(at: folderPathUrl)
}
try? data.write(to: folderPathUrl)
}

最新更新