问题描述
我将我的 pdfData 提供给用户保存.他可以保存到文件并制作文件,但pdf文件的默认名称是:PDF document.pdf
.如果可能的话,我想要我自己的文件名.也许我可以在将 pdfData 提供给 UIActivityViewController
之前更改 pdfData 中的文件名?
I give my pdfData to user to save. He can save to files and make a file, but the default name of the pdf file is: PDF document.pdf
. I want my own filename if this is possible. Perhaps I can change the filename within the pdfData before I give pdfData to UIActivityViewController
?
这是我的代码:
// Create page rect
let pageRect = CGRect(x: 0, y: 0, width: 595.28, height: 841.89) // A4, 72 dpi
// Create PDF context and draw
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, pageRect, nil)
UIGraphicsBeginPDFPage()
// From here you can draw page, best make it in a function
PdfErstellung.PdfErstellen(auswahlZeilen, vitalstoffWerteListe, heuteString)
UIGraphicsEndPDFContext()
// Save pdf DATA through user
let activityViewController = UIActivityViewController(activityItems: [pdfData], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // für IPAD nötig
self.present(activityViewController, animated: true, completion: nil)
-- 更新--
我的新想法是,先尝试保存文件并尝试URL,如果失败,则直接使用pdfData,因为在某些模拟器中使用URL不会出错,而在其他情况下会出错.
My new idea ist, first try save the file and try a URL, and if this fail, then use the pdfData directly, because in some simulator use URL give no error and in other give error.
更多信息:https://stackoverflow.com/a/52499637/10392572
推荐答案
您只需将您的 pdfData 保存到一个临时文件 URL 并共享该 URL.
You just need to save your pdfData to a temporary fileURL and share that URL.
let temporaryFolder = FileManager.default.temporaryDirectory
let fileName = "document.pdf"
let temporaryFileURL = temporaryFolder.appendingPathComponent(fileName)
print(temporaryFileURL.path) // /Users/lsd/Library/Developer/XCPGDevices/E2003834-07AB-4833-B206-843DC0A52967/data/Containers/Data/Application/322D1F1D-4C97-474C-9040-FE5E740D38CF/tmp/document.pdf
do {
try pdfData.write(to: temporaryFileURL)
// your code
let activityViewController = UIActivityViewController(activityItems: [temporaryFileURL], applicationActivities: nil)
} catch {
print(error)
}
这篇关于如何为 PDF 数据提供文件名以供用户在 Swift 中保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!