I am trying to export a PDF with a password protection. Currently, My app directly exports the PDF File to the iOS Files app... How do I password protect it before exporting it?
Here's my current code, Please do let me know what I have to change to achive this.
func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {
guard scan.pageCount >= 1 else {
controller.dismiss(animated: true)
return
}
var arrImages = [UIImage]()
for i in 0...scan.pageCount-1 {
let originalImage = scan.imageOfPage(at: i)
let fixedImage = reloadedImage(originalImage)
arrImages.append(fixedImage)
}
controller.dismiss(animated: true)
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let docURL = documentDirectory.appendingPathComponent("ScannedImage.pdf")
let data = createNewPDF(arrImage: arrImages)
do{
try data?.write(to: docURL)
print("Success")
}catch(let error){
print("error is \(error.localizedDescription)")
}
}
The PDF Creation Functions
func createPDF(image: UIImage) -> NSData? {
let pdfData = NSMutableData()
let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)!
var mediaBox = CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height)
let pdfContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!
pdfContext.beginPage(mediaBox: &mediaBox)
pdfContext.draw(image.cgImage!, in: mediaBox)
pdfContext.endPage()
let activityViewController = UIActivityViewController(activityItems: [pdfData], applicationActivities: nil)
present(activityViewController, animated: true, completion: nil)
return pdfData
}
func createNewPDF(arrImage: [UIImage]) -> Data? {
let pdfDocument = PDFDocument()
for i in 0...arrImage.count-1 {
let pdfPage = PDFPage(image: arrImage[i])
pdfDocument.insert(pdfPage!, at: i)
}
let pdfData = pdfDocument.dataRepresentation()
let activityViewController = UIActivityViewController(activityItems: [pdfData!], applicationActivities: nil)
present(activityViewController, animated: true, completion: nil)
return pdfData
}
Please do let me know if you need anything else.... Thanks in advance!