> 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/core/get-started/samples/pdfdocmemorytest.md).

# Read & Write PDF in Memory Buffer - PDFDocMemory

Sample 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.

Sample code for using Apryse SDK to read/write a PDF document from/to memory buffer; provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. 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 [Server SDK](/core/get-started/get-started.md).

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

```csharp
//
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
//

using System;
using System.IO;
using pdftron;
using pdftron.Common;
using pdftron.Filters;
using pdftron.SDF;
using pdftron.PDF;

// 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.
namespace PDFDocMemoryTestCS
{
	class Class1
	{
		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
		static Class1() {}
		
		[STAThread]
		static void Main(string[] args)
		{
			PDFNet.Initialize(PDFTronLicense.Key);

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

			try  
			{
				// Read a PDF document from a stream or pass-in a memory buffer...
				FileStream istm = new FileStream(input_path + "tiger.pdf", FileMode.Open, FileAccess.Read);
				using (PDFDoc doc = new PDFDoc(istm))
				using (ElementWriter writer = new ElementWriter())
				using (ElementReader reader = new ElementReader())
				{
					doc.InitSecurityHandler();

					int num_pages = doc.GetPageCount();

					Element element;

					// Perform some document editing ...
					// Here we simply copy all elements from one page to another.
					for(int i = 1; i <= num_pages; ++i)
					{
						Page pg = doc.GetPage(2 * i - 1);

						reader.Begin(pg);
						Page new_page = doc.PageCreate(pg.GetMediaBox());
						doc.PageInsert(doc.GetPageIterator(2*i), new_page);

						writer.Begin(new_page);
						while ((element = reader.Next()) != null) 	// Read page contents
						{
							writer.WriteElement(element);
						}

						writer.End();
						reader.End();
					}

					doc.Save(output_path + "doc_memory_edit.pdf", SDFDoc.SaveOptions.e_remove_unused);

					// Save the document to a stream or a memory buffer...
					using (FileStream ostm = new FileStream(output_path + "doc_memory_edit.txt", FileMode.Create, FileAccess.Write)) {
						doc.Save(ostm, SDFDoc.SaveOptions.e_remove_unused);
					}

					// Read some data from the file stored in memory
					reader.Begin(doc.GetPage(1));
					while ((element = reader.Next()) != null) {
						if (element.GetType() == Element.Type.e_path)
							Console.Write("Path, ");
					}
					reader.End();

					Console.WriteLine("");
					Console.WriteLine("");
					Console.WriteLine("Done. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...");
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}
			PDFNet.Terminate();
		}
	}
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code lineNumbers="true" %}

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

#include <PDF/PDFNet.h>
#include <PDF/PDFDoc.h>
#include <Filters/MappedFile.h>
#include <Filters/FilterReader.h>
#include <Filters/FilterWriter.h>
#include <PDF/ElementWriter.h>
#include <PDF/ElementReader.h>

#include <iostream>
#include <fstream>
#include "../../LicenseKey/CPP/LicenseKey.h"

using namespace std;
using namespace pdftron;
using namespace SDF;
using namespace PDF;
using namespace Filters;

int main(int argc, char *argv[])
{
	int ret = 0;
	PDFNet::Initialize(LicenseKey);

	// Relative path to the folder containing test files.
	string input_path =  "../../TestFiles/";
	string 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.
		MappedFile file((input_path + "tiger.pdf"));
		size_t file_sz = file.FileSize();
		
		FilterReader file_reader(file);

		unsigned char* mem = new unsigned char[file_sz];
		file_reader.Read((unsigned char*)mem, file_sz);
		PDFDoc doc(mem, file_sz);
		delete[] mem;

		doc.InitSecurityHandler();
		int num_pages = doc.GetPageCount();

		ElementWriter writer;
		ElementReader reader;
		Element element;

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

			reader.Begin(itr.Current());
			Page new_page = doc.PageCreate(itr.Current().GetMediaBox());
			PageIterator next_page = itr;
			next_page.Next(); 
			doc.PageInsert(next_page, new_page );

			writer.Begin(new_page);
			while ((element = reader.Next()) !=0) 	// Read page contents
			{
				//if (element.GetType() == Element::e_path)
				writer.WriteElement(element);
			}

			writer.End();
			reader.End();
		}

		doc.Save((output_path + "doc_memory_edit.pdf").c_str(), SDFDoc::e_remove_unused, NULL);
		// doc.Save((output_path + "doc_memory_edit.pdf").c_str(), Doc::e_linearized, NULL);

		// Save the document to a memory buffer.
		const char* buf = 0; 
		size_t buf_sz;

		doc.Save(buf, buf_sz, SDFDoc::e_remove_unused, NULL);
		// doc.Save(buf, buf_sz, Doc::e_linearized, NULL);

		// Write the contents of the buffer to the disk
		{
			ofstream out((output_path + "doc_memory_edit.txt").c_str(), ofstream::binary);
			out.write(buf, buf_sz);
			out.close();
		}

		// Read some data from the file stored in memory
		reader.Begin(doc.GetPage(1));
		while ((element = reader.Next()) !=0) {
			if (element.GetType() == Element::e_path) cout << "Path, ";
		}
		reader.End();

		cout << "\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ..." << endl;
	}
	catch(Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch(...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	PDFNet::Terminate();
	return ret;
}
```

{% endcode %}
{% endtab %}

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

```go
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------

package main
import (
    "fmt"
    "os"
    . "pdftron"
)

import  "pdftron/Samples/LicenseKey/GO"

func main(){
    PDFNetInitialize(PDFTronLicense.Key)
    
    // Relative path to the folder containing the test files.
    inputPath := "../../TestFiles/"
    outputPath := "../../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.
    
    // Read a PDF document in a memory buffer.
    file := NewMappedFile(inputPath + "tiger.pdf")
    fileSZ := file.FileSize()
    
    fileReader := NewFilterReader(file)
    
    mem := fileReader.Read(fileSZ)
    memBytes := make([]byte, int(mem.Size()))
    for i := 0; i < int(mem.Size()); i++{
        memBytes[i] = mem.Get(i)
    }
    doc := NewPDFDoc(&memBytes[0], fileSZ)
    doc.InitSecurityHandler()
    numPages := doc.GetPageCount()
    
    writer := NewElementWriter()
    reader := NewElementReader()
    element := NewElement()
    
    // Create a duplicate of every page but copy only path objects
    
    i := 1
    for i <= numPages{
        itr := doc.GetPageIterator(uint(2*i - 1))
        
        reader.Begin(itr.Current())
        new_page := doc.PageCreate(itr.Current().GetMediaBox())
        next_page := itr
        next_page.Next()
        doc.PageInsert(next_page, new_page)
        
        writer.Begin(new_page)
        element = reader.Next()
        for element.GetMp_elem().Swigcptr() != 0 { // Read page contents
            //if element.GetType() == Element.e_path:
            writer.WriteElement(element)
            element = reader.Next()
        }
        writer.End()
        reader.End()           
        i = i + 1
    }
    doc.Save(outputPath + "doc_memory_edit.pdf", uint(SDFDocE_remove_unused))
    
    // Save the document to a memory buffer
    buffer := (doc.Save(uint(SDFDocE_remove_unused))).(VectorUnChar)

    // Write the contents of the buffer to the disk
    bufferBytes := make([]byte, int(buffer.Size()))
    for i := 0; i < int(buffer.Size()); i++{
        bufferBytes[i] = buffer.Get(i)
    }
    f, err := os.Create(outputPath + "doc_memory_edit.txt")

    if err != nil {
        fmt.Println(err)
    }
    defer f.Close()
    _, err2 := f.Write(bufferBytes)
    if err2 != nil {
        fmt.Println(err2)
    }

    // Read some data from the file stored in memory
    reader.Begin(doc.GetPage(1))
    element = reader.Next()
    for element.GetMp_elem().Swigcptr() != 0{
        if element.GetType() == ElementE_path{
            os.Stdout.Write([]byte("Path, "))
        }
        element = reader.Next()
    }
    reader.End()
    
    PDFNetTerminate()
    fmt.Println("\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...")
}
```

{% endcode %}
{% endtab %}

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

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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.pdftron.common.PDFNetException;
import com.pdftron.filters.FilterReader;
import com.pdftron.filters.FilterWriter;
import com.pdftron.filters.MappedFile;
import com.pdftron.pdf.*;
import com.pdftron.sdf.SDFDoc;

public class PDFDocMemoryTest {

    public static void main(String[] args) {

        PDFNet.initialize(PDFTronLicense.Key());

        // Relative path to the folder containing test files.
        String input_path = "../../TestFiles/";
        String 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.
            MappedFile file = new MappedFile((input_path + "tiger.pdf"));
            long file_sz = file.fileSize();

            FilterReader file_reader = new FilterReader(file);

            byte[] mem = new byte[(int) file_sz];

            long bytes_read = file_reader.read(mem);
            try (PDFDoc doc = new PDFDoc(mem)) {

                doc.initSecurityHandler();
                int num_pages = doc.getPageCount();

                ElementWriter writer = new ElementWriter();
                ElementReader reader = new ElementReader();
                Element element;

                // Create a duplicate of every page but copy only path objects

                for (int i = 1; i <= num_pages; ++i) {
                    PageIterator itr = doc.getPageIterator(2 * i - 1);
                    Page current = itr.next();
                    reader.begin(current);
                    Page new_page = doc.pageCreate(current.getMediaBox());
                    doc.pageInsert(itr, new_page);

                    writer.begin(new_page);
                    while ((element = reader.next()) != null)    // Read page contents
                    {
                        //if (element.getType() == Element.e_path)
                        writer.writeElement(element);
                    }

                    writer.end();
                    reader.end();
                }

                doc.save(output_path + "doc_memory_edit.pdf", SDFDoc.SaveMode.REMOVE_UNUSED, null);

                // Save the document to a memory buffer.


                byte[] buf = doc.save(SDFDoc.SaveMode.REMOVE_UNUSED, null);
                // doc.Save(buf, buf_sz, Doc::e_linearized, NULL);

                // Write the contents of the buffer to the disk
                {
                    File outfile = new File(output_path + "doc_memory_edit.txt");
                    // output "doc_memory_edit.txt"
                    FileOutputStream fop = new FileOutputStream(outfile);
                    if (!outfile.exists()) {
                        outfile.createNewFile();
                    }
                    fop.write(buf);
                    fop.flush();
                    fop.close();
                }

                // Read some data from the file stored in memory
                reader.begin(doc.getPage(1));
                while ((element = reader.next()) != null) {
                    if (element.getType() == Element.e_path) System.out.print("Path, ");
                }
                reader.end();
                
                System.out.println("\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...");
            }
        }
        catch (PDFNetException e)
        {
            e.printStackTrace();
            System.out.println(e);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        PDFNet.terminate();
    }
}
```

{% endcode %}
{% endtab %}

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

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

const fs = require('fs');
const { PDFNet } = require('@pdftron/pdfnet-node');
const PDFTronLicense = require('../LicenseKey/LicenseKey');

((exports) => {
  'use strict';

  exports.runPDFDocMemoryTest = () => {
    const main = async () => {
      const outputPath = '../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.
        const file = await PDFNet.Filter.createMappedFileFromUString('../TestFiles/tiger.pdf');
        const file_sz = await file.mappedFileFileSize();

        const file_reader = await PDFNet.FilterReader.create(file);

        const mem = await file_reader.read(file_sz);
        const doc = await PDFNet.PDFDoc.createFromBuffer(mem);

        doc.initSecurityHandler();
        const num_pages = await doc.getPageCount();

        const writer = await PDFNet.ElementWriter.create();
        const reader = await PDFNet.ElementReader.create();

        // Create a duplicate of every page but copy only path objects
        for (let i = 1; i <= num_pages; ++i) {
          const itr = await doc.getPageIterator(2 * i - 1);

          const cur_page = await itr.current();
          reader.beginOnPage(cur_page);
          const new_page = await doc.pageCreate(await cur_page.getMediaBox());
          itr.next();
          doc.pageInsert(itr, new_page);

          writer.beginOnPage(new_page);
          var element;
          while (element = await reader.next()) {	// Read page contents
            writer.writeElement(element);
          }

          await writer.end();
          await reader.end();
        }

        doc.save(outputPath + 'doc_memory_edit.pdf', PDFNet.SDFDoc.SaveOptions.e_remove_unused);

        // Save the document to a memory buffer.
        const docbuf = await doc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_remove_unused);

        // Write the contents of the buffer to the disk
        fs.appendFileSync(outputPath + 'doc_memory_edit.txt', docbuf);

        let dataStr = ''
        // Read some data from the file stored in memory
        reader.beginOnPage(await doc.getPage(1));
        while (element = await reader.next()) {
          if (await element.getType() == PDFNet.Element.Type.e_path) dataStr += 'Path, ';
        }
        reader.end();
        console.log(dataStr);

        console.log('\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...');
      } catch (err) {
        console.log(err);
      }
    }
    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error) {
      console.log('Error: ' + JSON.stringify(error));
    }).then(function(){ return PDFNet.shutdown(); });
  };
  exports.runPDFDocMemoryTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=PDFDocMemoryTest.js
```

{% endcode %}
{% endtab %}

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

```php
<?php
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
include("../../../PDFNetC/Lib/PDFNetPHP.php");
include("../../LicenseKey/PHP/LicenseKey.php");

// Relative path to the folder containing the test files.
$input_path = getcwd()."/../../TestFiles/";
$output_path = $input_path."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.
	
	PDFNet::Initialize($LicenseKey);
	PDFNet::GetSystemFontList();    // Wait for fonts to be loaded if they haven't already. This is done because PHP can run into errors when shutting down if font loading is still in progress.
	
	// Read a PDF document in a memory buffer.
	$file = new MappedFile($input_path."tiger.pdf");
	$file_sz = $file->FileSize();
        
	$file_reader = new FilterReader($file);
	$mem = $file_reader->Read($file_sz);
	$test = array();
	for ($i = 0; $i < strlen($mem); $i++) {
		$test[] = ord($mem[$i]);
	}
	$doc = new PDFDoc($mem, $file_sz);
	$doc->InitSecurityHandler();
	$num_pages = $doc->GetPageCount();

	$writer = new ElementWriter();
	$reader = new ElementReader();

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

		$reader->Begin($itr->Current());
		$new_page = $doc->PageCreate($itr->Current()->GetMediaBox());
		$next_page = $itr;
		$next_page->Next(); 
		$doc->PageInsert($next_page, $new_page);

		$writer->Begin($new_page);
		while (($element = $reader->Next()) !=null) 	// Read page contents
		{
			//if ($element->GetType() == Element::e_path)
            $writer->WriteElement($element);
		}

		$writer->End();
		$reader->End();
	}

	$doc->Save($output_path."doc_memory_edit.pdf", SDFDoc::e_remove_unused);

	// Save the document to a memory buffer.
	$buffer = $doc->Save(SDFDoc::e_remove_unused);

	// Write the contents of the buffer to the disk
    $outfile = fopen($output_path."doc_memory_edit.txt", "w");
    fwrite($outfile, $buffer);
    fclose($outfile);;

	// Read some data from the file stored in memory
	$reader->Begin($doc->GetPage(1));
	while (($element = $reader->Next()) !=null) {
		if ($element->GetType() == Element::e_path) echo "Path, ";
	}
	$reader->End();
	PDFNet::Terminate();
	echo nl2br("\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...\n");
?>
```

{% endcode %}
{% endtab %}

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

```python
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

import site
site.addsitedir("../../../PDFNetC/Lib")
import sys
from PDFNetPython import *

sys.path.append("../../LicenseKey/PYTHON")
from LicenseKey import *

def main():
    PDFNet.Initialize(LicenseKey)
    
    # Relative path to the folder containing the test files.
    input_path = "../../TestFiles/"
    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.
    
    # Read a PDF document in a memory buffer.
    file = MappedFile(input_path + "tiger.pdf")
    file_sz = file.FileSize()
    
    file_reader = FilterReader(file)
    
    mem = file_reader.Read(file_sz)
    doc = PDFDoc(bytearray(mem), file_sz)
    doc.InitSecurityHandler()
    num_pages = doc.GetPageCount()
    
    writer = ElementWriter()
    reader = ElementReader()
    element = Element()
    
    # Create a duplicate of every page but copy only path objects
    
    i = 1
    while i <= num_pages:
        itr = doc.GetPageIterator(2*i - 1)
        
        reader.Begin(itr.Current())
        new_page = doc.PageCreate(itr.Current().GetMediaBox())
        next_page = itr
        next_page.Next()
        doc.PageInsert(next_page, new_page)
        
        writer.Begin(new_page)
        element = reader.Next()
        while element != None: # Read page contents
            #if element.GetType() == Element.e_path:
            writer.WriteElement(element)
            element = reader.Next()
        writer.End()
        reader.End()           
        i = i + 1
    
    doc.Save(output_path + "doc_memory_edit.pdf", SDFDoc.e_remove_unused)
    
    # Save the document to a memory buffer
    buffer = doc.Save(SDFDoc.e_remove_unused)
    
    # Write the contents of the buffer to the disk
    if sys.version_info.major >= 3:
        f = open(output_path + "doc_memory_edit.txt", "w")
    else:	
        f = open(output_path + "doc_memory_edit.txt", "wb")
    try:
        f.write(str(buffer))
    finally:
        f.close()
    
    # Read some data from the file stored in memory
    reader.Begin(doc.GetPage(1))
    element = reader.Next()
    while element != None:
        if element.GetType() == Element.e_path:
            sys.stdout.write("Path, ")
        element = reader.Next()
    reader.End()
    
    PDFNet.Terminate()
    print("\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...")

if __name__ == '__main__':
    main()
```

{% endcode %}
{% endtab %}

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

```ruby
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

require '../../../PDFNetC/Lib/PDFNetRuby'
include PDFNetRuby
require '../../LicenseKey/RUBY/LicenseKey'

$stdout.sync = true

# 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.

	PDFNet.Initialize(PDFTronLicense.Key)
	
	# Relative path to the folder containing the test files.
	input_path = "../../TestFiles/"
	output_path = "../../TestFiles/Output/"
	
	# Read a PDF document in a memory buffer.
	file = MappedFile.new((input_path + "tiger.pdf"))
	file_sz = file.FileSize
	
	file_reader = FilterReader.new(file)
	
	mem = file_reader.Read(file_sz)
	doc = PDFDoc.new(mem, file_sz)
	doc.InitSecurityHandler
	num_pages = doc.GetPageCount
	
	writer = ElementWriter.new
	reader = ElementReader.new
	element = Element.new
	
	# Create a duplicate of every page but copy only path objects
	
	i = 1
	while i <= num_pages do
		itr = doc.GetPageIterator(2*i - 1)
		
		reader.Begin(itr.Current)
		new_page = doc.PageCreate(itr.Current.GetMediaBox)
		next_page = itr
		next_page.Next
		doc.PageInsert(next_page, new_page)
		
		writer.Begin(new_page)
		element = reader.Next
		while !element.nil? do	# Read page contents
			#if element.GetType == Element::E_path
            writer.WriteElement(element)
			#end
			element = reader.Next
		end
		writer.End
		reader.End		   
		i = i + 1
	end
	
	doc.Save(output_path + "doc_memory_edit.pdf", SDFDoc::E_remove_unused)
	
	# Save the document to a memory buffer
	buffer = doc.Save(SDFDoc::E_remove_unused)
	
	# Write the contents of the buffer to the disk
    File.open(output_path + "doc_memory_edit.txt", 'w') { |file| file.write(buffer) }
	
	# Read some data from the file stored in memory
	reader.Begin(doc.GetPage(1))
	element = reader.Next
	while !element.nil? do
		if element.GetType == Element::E_path
			print "Path, "
		end
		element = reader.Next
	end
	reader.End
	PDFNet.Terminate
	puts "\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ..."
```

{% endcode %}
{% endtab %}

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

```vb
'
' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
'

Imports System
Imports System.IO

Imports pdftron
Imports pdftron.Common
Imports pdftron.Filters
Imports pdftron.SDF
Imports pdftron.PDF

' 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.
Module PDFDocMemoryTestVB
	Dim pdfNetLoader As PDFNetLoader
	Sub New()
		pdfNetLoader = pdftron.PDFNetLoader.Instance()
	End Sub

	Sub Main()

		PDFNet.Initialize(PDFTronLicense.Key)

		' Relative path to the folder containing test files.
		Dim input_path As String = "../../../../TestFiles/"
		Dim output_path As String = "../../../../TestFiles/Output/"

		Try
			' Read a PDF document in a memory buffer.
			Dim istm As FileStream = New FileStream(input_path + "tiger.pdf", FileMode.Open, FileAccess.Read)
			Using doc As PDFDoc = New PDFDoc(istm)
				doc.InitSecurityHandler()
				Dim num_pages As Integer = doc.GetPageCount()

				Using writer As ElementWriter = New ElementWriter
					Using reader As ElementReader = New ElementReader
						Dim element As Element

						' Perform some document editing ...
						' Here we simply copy all elements from one page to another.
						Dim i As Integer
						For i = 1 To num_pages Step 1
							Dim pg As Page = doc.GetPage(2 * i - 1)
							reader.Begin(pg)
							Dim new_page As Page = doc.PageCreate(pg.GetMediaBox())
							doc.PageInsert(doc.GetPageIterator(2 * i), new_page)

							writer.Begin(new_page)
							element = reader.Next()
							While (Not IsNothing(element))		' Read page contents
								writer.WriteElement(element)
								element = reader.Next()
							End While

							writer.End()
							reader.End()
						Next i

						doc.Save(output_path + "doc_memory_edit.pdf", SDF.SDFDoc.SaveOptions.e_remove_unused)

						' Save the document to a stream or a memory buffer...
						Dim ostm As FileStream = New FileStream(output_path + "doc_memory_edit.txt", FileMode.Create, FileAccess.Write)
						doc.Save(ostm, SDF.SDFDoc.SaveOptions.e_remove_unused)
						ostm.Close()

						' Read some data from the file stored in memory
						reader.Begin(doc.GetPage(1))
						element = reader.Next()
						While (Not IsNothing(element))	 ' Read page contents
							If element.GetType() = element.Type.e_path Then
								Console.Write("Path, ")
							End If

							element = reader.Next()
						End While
						reader.End()
					End Using
				End Using
			End Using
			Console.WriteLine("")
			Console.WriteLine("")
			Console.WriteLine("Done. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...")
		Catch ex As PDFNetException
			Console.WriteLine(ex.Message)
		Catch ex As Exception
			MsgBox(ex.Message)
		End Try
		PDFNet.Terminate()
	End Sub
End Module
```

{% 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/core/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.
