如何用Swift存储并修改文档或PDF中的指定预定义字段?
Absolutely! You can store documents or PDFs in your Swift app's file system and modify predefined fields like [INPUT1], [INPUT2]—though the approach varies a bit depending on whether you're working with plain text-based documents or PDFs. Let's break this down step by step.
First, you'll want to store your template files in a persistent location. The Documents directory in your app's sandbox is the most common choice—it's retained between app launches, and you can enable file sharing so users can access it via the Files app (add UIFileSharingEnabled to your Info.plist if you want this).
Here's how to copy a template from your app bundle to the Documents directory:
func copyTemplateToDocuments() throws { guard let templateURL = Bundle.main.url(forResource: "Template", withExtension: "txt") else { throw NSError(domain: "AppError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Template file not found"]) } let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let destinationURL = documentsDir.appendingPathComponent("ModifiedTemplate.txt") // Only copy if the file doesn't exist already if !FileManager.default.fileExists(atPath: destinationURL.path) { try FileManager.default.copyItem(at: templateURL, to: destinationURL) } }
This is straightforward since these formats are easily convertible to strings. The workflow is:
- Read the file content into a string
- Replace placeholder values
- Write the modified content back to the file
Example code:
func modifyTextDocument() throws { let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let fileURL = documentsDir.appendingPathComponent("ModifiedTemplate.txt") // Read the file content var content = try String(contentsOf: fileURL, encoding: .utf8) // Define your placeholder replacements let replacements = [ "[INPUT1]": "your custom text", "[INPUT2]": "15th century" ] // Replace all placeholders replacements.forEach { placeholder, value in content = content.replacingOccurrences(of: placeholder, with: value) } // Write the modified content back try content.write(to: fileURL, atomically: true, encoding: .utf8) }
PDFs are trickier because they're structured binary files, not plain text. You have two reliable approaches:
Approach 1: Use PDFKit for AcroForm Templates
If your PDF is an AcroForm template (with editable form fields named INPUT1, INPUT2, etc.), this is the simplest method. You can directly set values for these fields without breaking formatting:
import PDFKit func modifyPDFForm() throws { let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let templateURL = Bundle.main.url(forResource: "FormTemplate", withExtension: "pdf")! let outputURL = documentsDir.appendingPathComponent("FilledForm.pdf") guard let pdfDocument = PDFDocument(url: templateURL) else { throw NSError(domain: "AppError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Failed to load PDF"]) } // Set values for form fields pdfDocument.setValue("John Doe", forField: "INPUT1") pdfDocument.setValue("1990", forField: "INPUT2") // Save the modified PDF guard pdfDocument.write(to: outputURL) else { throw NSError(domain: "AppError", code: 3, userInfo: [NSLocalizedDescriptionKey: "Failed to save PDF"]) } }
Approach 2: Replace Text Placeholders in Non-Form PDFs
If your PDF doesn't use form fields, you'll need to locate and replace placeholder text directly. This works best for simple, single-line placeholders—note that longer/shorter replacement text may break formatting (font size, spacing, alignment).
Here's a basic example using PDFKit:
import PDFKit func replaceTextInPDF() throws { let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let templateURL = Bundle.main.url(forResource: "TextTemplate", withExtension: "pdf")! let outputURL = documentsDir.appendingPathComponent("ModifiedPDF.pdf") guard let pdfDocument = PDFDocument(url: templateURL) else { throw NSError(domain: "AppError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Failed to load PDF"]) } for pageIndex in 0..<pdfDocument.pageCount { guard let page = pdfDocument.page(at: pageIndex) else { continue } guard let contentStream = page.contentStream else { continue } // Replace placeholders in the content stream var modifiedContent = contentStream modifiedContent = modifiedContent.replacingOccurrences(of: "[INPUT1]", with: "Custom Value") modifiedContent = modifiedContent.replacingOccurrences(of: "[INPUT2]", with: "15th Century") // Update the page with modified content let mutablePage = page.copy() as! PDFPage mutablePage.replaceContentStream(modifiedContent) pdfDocument.replacePage(at: pageIndex, with: mutablePage) } // Save the modified PDF guard pdfDocument.write(to: outputURL) else { throw NSError(domain: "AppError", code: 3, userInfo: [NSLocalizedDescriptionKey: "Failed to save PDF"]) } }
Key Notes for PDF Modification:
- For production apps, using AcroForm templates is always preferable—it avoids formatting issues and is more reliable.
- If you need advanced PDF editing (like dynamic text sizing or complex layouts), consider third-party libraries (though many require paid licenses).
内容的提问来源于stack exchange,提问作者sn22

