Skip to content

Instantly share code, notes, and snippets.

@benbahrenburg
Last active November 27, 2019 09:16
Show Gist options
  • Save benbahrenburg/9b56bd9f598b6632b0826faae0f9b9e8 to your computer and use it in GitHub Desktop.
Save benbahrenburg/9b56bd9f598b6632b0826faae0f9b9e8 to your computer and use it in GitHub Desktop.
Copy CGPDFDocument to Data
if let pdf = unlock(data: pdfData, password: "Hello World") {
print("You now have an unlocked CGPDFDocument")
print("Create a copy of the unlocked CGPDFDocument")
let pdfWithoutPassword = copyPDFtoData(pdf: pdf)
print("You how have a pdf without password information")
}
func copyPDFtoData(pdf: CGPDFDocument) -> Data {
let data = NSMutableData()
autoreleasepool {
let pageCount = pdf.numberOfPages
UIGraphicsBeginPDFContextToData(data, .zero, nil)
for index in 1...pageCount {
let page = pdf.page(at: index)
let pageRect = page?.getBoxRect(CGPDFBox.mediaBox)
UIGraphicsBeginPDFPageWithInfo(pageRect!, nil)
let ctx = UIGraphicsGetCurrentContext()
ctx?.interpolationQuality = .high
// Draw existing page
ctx!.saveGState()
ctx!.scaleBy(x: 1, y: -1)
ctx!.translateBy(x: 0, y: -(pageRect?.size.height)!)
ctx!.drawPDFPage(page!)
ctx!.restoreGState()
}
UIGraphicsEndPDFContext()
}
return data as Data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment