> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/ios/get-started/samples/pdfdocmemorytest.md).

# PDFDocMemory

Sample Obj-C code for using Apryse 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 d

Sample Obj-C code for using Apryse 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 [iOS SDK](/ios/guides.md).

{% tabs %}
{% tab title="Obj-C" %}
{% code lineNumbers="true" %}

```objc
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

#import <OBJC/PDFNetOBJC.h>
#import <Foundation/Foundation.h>

int main(int argc, char *argv[])
{
    @autoreleasepool {
        int ret = 0;
        [PTPDFNet Initialize: 0];

        // Relative path to the folder containing test files.
        NSString *input_path = @"../../TestFiles/";
        NSString *output_path = @"../../TestFiles/Output/";


        // 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.
        @try  
        {
            // Read a PDF document in a memory buffer.
            PTMappedFile *file = [[PTMappedFile alloc] initWithFilename: @"../../TestFiles/tiger.pdf"];
            unsigned long file_sz = [file FileSize];
        
            PTFilterReader *file_reader = [[PTFilterReader alloc] initWithFilter: file];

            NSData *mem = [file_reader Read: file_sz];
            PTPDFDoc *doc = [[PTPDFDoc alloc] initWithBuf: mem buf_size: file_sz];

            [doc InitSecurityHandler];
            int num_pages = [doc GetPageCount];

            PTElementWriter *writer = [[PTElementWriter alloc] init];
            PTElementReader *reader = [[PTElementReader alloc] init];
            PTElement *element;

            // Create a duplicate of every page but copy only path objects
            int i;
            for(i=1; i<=num_pages; ++i)
            {
                PTPageIterator *itr = [doc GetPageIterator: 2*i-1];

                [reader Begin: [itr Current]];
                PTPage *new_page = [doc PageCreate: [[itr Current] GetMediaBox]];
                PTPageIterator *next_page = itr;
                [next_page Next]; 
                [doc PageInsert: next_page page: new_page];

                [writer WriterBeginWithPage: new_page placement: e_ptoverlay page_coord_sys: YES compress: YES resources: NULL];
                while ((element = [reader Next]) != NULL)    // Read page contents
                {
                    //if ([element GetType] == e_ptpath)
                [writer WriteElement: element];
                }

                [writer End];
                [reader End];
            }

        [doc SaveToFile: @"../../TestFiles/Output/doc_memory_edit.pdf" flags: e_ptremove_unused];
        //[doc SaveToFile: @"../../TestFiles/Output/doc_memory_edit.pdf" flags: e_ptlinearized];
        
            // Save the document to a memory buffer.
            NSData *buf = [doc SaveToBuf: e_ptremove_unused];
            // NSData *buf = [doc SaveToBuf: e_ptlinearized];

            // Write the contents of the buffer to the disk
            {
            [buf writeToFile: @"../../TestFiles/Output/doc_memory_edit.txt" atomically: NO];
            }

            // Read some data from the file stored in memory
            [reader Begin: [doc GetPage: 1]];
            while ((element = [reader Next]) !=0) {
                if ([element GetType] == e_ptpath) printf("%s", "Path, ");
            }
            [reader End];

            printf("\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...\n");
        }
        @catch(NSException *e)
        {
            NSLog(@"%@", e.reason);
            ret = 1;
        }
        [PTPDFNet Terminate: 0];            
        return ret;

    }
}
```

{% endcode %}
{% endtab %}

{% tab title="Swift" %}
{% code lineNumbers="true" %}

```swift
//---------------------------------------------------------------------------------------
// 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
    }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/ios/get-started/samples/pdfdocmemorytest.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
