Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 = index)
let pageRect = page?.getBoxRect(CGPDFBox.mediaBox)
UIGraphicsBeginPDFPageWithInfo(pageRect!, nil)
let ctx = UIGraphicsGetCurrentContext()
ctx?.interpolationQuality = .high
// Draw existing page
ctx!.scaleBy(x: 1, y: -1)
ctx!.translateBy(x: 0, y: -(pageRect?.size.height)!)
return data as Data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment