Search code examples
swiftmacoscocoapdfkitcgcontext

Displaying modified PDF page in PDF View without saving locally


I am using the following code to write a text on a PDF. I need to display the modified PDF page using PDFView.I cannot find a way to display the modified PDF page on the PDF View without saving the modified PDF locally and loading it from disc. Is there a way to display the PDF file in the PDF you without saving it first?

    let input = getSelectedFilename()
    let dstURL = URL(fileURLWithPath: "/Users/me/Downloads/out.pdf")
    
    var pdffile=PDFDocument(url: input)
    let page: PDFPage = pdffile!.page(at: 0)!
    
    let bounds = page.bounds(for: PDFDisplayBox.mediaBox)
    let size = bounds.size
    
    var mediaBox: CGRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    
    
    let context = CGContext(dstURL as CFURL, mediaBox: &mediaBox, nil)
    let graphicsContext = NSGraphicsContext(cgContext: context!, flipped: false)
    NSGraphicsContext.current = graphicsContext
    
    context!.beginPDFPage(nil)
    text.draw(in:drawrect,withAttributes:textFontAttributes);
    
    context!.saveGState()
    
    context!.restoreGState()
    
    context!.endPDFPage()
    NSGraphicsContext.current = nil
    context?.closePDF()
    var pdffile2=PDFDocument(url: dstURL)
    pdfview.document=pdffile2

Solution

  • You can create a PDFDocument from Data. Use .dataRepresentation() on your PDFDocument to get the data, and PDFDocument(data: ) to create the PDFDocument from the data.

    let data = myPDFDocument.dataRepresentation()
    let anotherDocument = PDFDocument(data: data)