how to edit a PDF in objective-c?

后端 未结 3 1871
名媛妹妹
名媛妹妹 2020-12-05 01:18

i\'m writing an application in objective-c (using cocoa). i have a PDF template, i need to substitute actual values into placeholders in PDF and then save the result into ne

3条回答
  •  温柔的废话
    2020-12-05 02:04

    I know that the question is about obj-c, but if you are here because of the edit pdf, below there is a solution in Swift 3:

    PS: In my solution I needed to edit the document info of the new PDF, so I used the subject parameter to do this.

    func createPDF(on path: String?, from templateURL: URL?, with subject: String?) {
        guard let newPDFPath = path,
            let pdfURL = templateURL else { return }
    
        let options = [(kCGPDFContextSubject as String): subject ?? ""] as CFDictionary
    
        UIGraphicsBeginPDFContextToFile(newPDFPath, .zero, options as? [AnyHashable : Any])
    
        let templateDocument = CGPDFDocument(pdfURL as CFURL)
        let pageCount = templateDocument?.numberOfPages ?? 0
    
        for i in 1...pageCount {
    
            //get bounds of template page
            if let templatePage = templateDocument?.page(at: i) {
                let templatePageBounds = templatePage.getBoxRect(.cropBox)
    
                //create empty page with corresponding bounds in new document
                UIGraphicsBeginPDFPageWithInfo(templatePageBounds, nil)
                let context = UIGraphicsGetCurrentContext()
    
                //flip context due to different origins
                context?.translateBy(x: 0.0, y: templatePageBounds.height)
                context?.scaleBy(x: 1.0, y: -1.0)
    
                //copy content of template page on the corresponding page in new file
                context?.drawPDFPage(templatePage)
    
                //flip context back
                context?.translateBy(x: 0.0, y: templatePageBounds.height)
                context?.scaleBy(x: 1.0, y: -1.0)
            }
        }
        UIGraphicsEndPDFContext()
    }
    

提交回复
热议问题