Some test text!

Discord Logo

Chat with us

PDFTron is now Apryse, learn more here.

Read & write a PDF file from/to memory buffer in Swift

More languages

More languages
Java (Android)
C++
C#
C# (.NET Core)
Go
Java
Kotlin
Obj-C
JS (Node.js)
PHP
Python
Ruby
Swift
C# (UWP)
VB
C# (Xamarin)

Sample Swift code for using PDFTron SDK to read/write a PDF document from/to memory buffer. This is useful for applications that work with dynamic PDFdocuments that don't need to be saved/read from a disk. Learn more about our Swift PDF Library.

Get Started Samples Download

To run this sample, get started with a free trial of Apryse SDK.

//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import PDFNet
import Foundation

func runPDFDocMemoryTest() -> Int {
    return autoreleasepool {
        var ret = 0
        
        
        // The following sample illustrates how to read/write a PDF document from/to
        // a memory buffer.  This is useful for applications that work with dynamic PDF
        // documents that don't need to be saved/read from a disk.
        do {
            try PTPDFNet.catchException {
                // Read a PDF document in a memory buffer.
                let file: PTMappedFile = PTMappedFile(filename: Bundle.main.path(forResource: "tiger", ofType: "pdf"))
                let file_sz: UInt = file.fileSize()
                
                let file_reader: PTFilterReader = PTFilterReader(filter: file)
                
                let mem: Data = file_reader.read(file_sz)
                let doc: PTPDFDoc = PTPDFDoc(buf: mem, buf_size: file_sz)
                
                doc.initSecurityHandler()
                let num_pages = doc.getPageCount()
                
                let writer: PTElementWriter = PTElementWriter()
                let reader: PTElementReader = PTElementReader()
                
                // Create a duplicate of every page but copy only path objects
                for i in 1...num_pages {
                    let itr: PTPageIterator = doc.getPageIterator(UInt32(2 * i - 1))
                    
                    reader.begin(itr.current())
                    let new_page: PTPage = doc.pageCreate(itr.current().getMediaBox())
                    let next_page: PTPageIterator = itr
                    next_page.next()
                    doc.pageInsert(next_page, page: new_page)
                    
                    writer.writerBegin(with: new_page, placement: e_ptoverlay, page_coord_sys: true, compress: true, resources: nil)
                    while let element = reader.next() {
                        //if element.getType() == e_ptpath
                        writer.write(element)
                    }
                    
                    writer.end()
                    reader.end()
                }
                
                doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("doc_memory_edit.pdf").path, flags: e_ptremove_unused.rawValue)
                //doc.save(toFile: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("doc_memory_edit.pdf").path, flags: e_ptlinearized)
                
                // Save the document to a memory buffer.
                let buf: Data = doc.save(toBuf: e_ptremove_unused.rawValue)
                //let buf: Data = doc.save(toBuf: e_ptlinearized.rawValue)
                
                // Write the contents of the buffer to the disk
                do {
                    try buf.write(to: URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]).appendingPathComponent("doc_memory_edit.txt"), options: .atomic)
                } catch {
                    
                }
                
                // Read some data from the file stored in memory
                reader.begin(doc.getPage(1))
                while let element = reader.next() {
                    if element.getType() == e_ptpath {
                        print("\("Path, ")")
                    }
                }
                reader.end()
                
                print("Done. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...")
            }
        } catch let e as NSError {
            print("\(e)")
            ret = 1
        }
        return ret
    }
}