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

# PDFDocMemory

Sample Java 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 di

Sample Java 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 [Android SDK](/core/get-started/languages/java.md).

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

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

package com.pdftron.android.pdfnetsdksamples.samples;

import com.pdftron.android.pdfnetsdksamples.OutputListener;
import com.pdftron.android.pdfnetsdksamples.PDFNetSample;
import com.pdftron.android.pdfnetsdksamples.R;
import com.pdftron.android.pdfnetsdksamples.util.Utils;
import com.pdftron.common.PDFNetException;
import com.pdftron.filters.FilterReader;
import com.pdftron.filters.MappedFile;
import com.pdftron.pdf.Element;
import com.pdftron.pdf.ElementReader;
import com.pdftron.pdf.ElementWriter;
import com.pdftron.pdf.PDFDoc;
import com.pdftron.pdf.Page;
import com.pdftron.pdf.PageIterator;
import com.pdftron.sdf.SDFDoc;

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

public class PDFDocMemoryTest extends PDFNetSample {

	private static OutputListener mOutputListener;

	private static ArrayList<String> mFileList = new ArrayList<>();

    public PDFDocMemoryTest() {
        setTitle(R.string.sample_pdfdocmemory_title);
        setDescription(R.string.sample_pdfdocmemory_description);
    }

	@Override
	public void run(OutputListener outputListener) {
		super.run(outputListener);
		mOutputListener = outputListener;
		mFileList.clear();
		printHeader(outputListener);


        // 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((Utils.getAssetTempFile(INPUT_PATH + "tiger.pdf").getAbsolutePath()));
            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(Utils.createExternalFile("doc_memory_edit.pdf", mFileList).getAbsolutePath(), 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(Utils.createExternalFile("doc_memory_edit.txt", mFileList).getAbsolutePath());
                    // 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) mOutputListener.print("Path, ");
                }
                reader.end();
                
                mOutputListener.println("\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...");
            }
        }
        catch (PDFNetException e)
        {
            mOutputListener.printError(e.getStackTrace());
            mOutputListener.printError(e.getStackTrace());
        }
        catch (Exception e)
        {
            mOutputListener.printError(e.getStackTrace());
        }

		for (String file : mFileList) {
			addToFileList(file);
		}
		printFooter(outputListener);
	}

}
```

{% endcode %}
{% endtab %}

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

```kotlin
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------
package com.pdftron.android.pdfnetsdksamples.samples

import com.pdftron.android.pdfnetsdksamples.OutputListener
import com.pdftron.android.pdfnetsdksamples.PDFNetSample
import com.pdftron.android.pdfnetsdksamples.R
import com.pdftron.android.pdfnetsdksamples.util.Utils
import com.pdftron.common.PDFNetException
import com.pdftron.filters.MappedFile
import com.pdftron.pdf.ElementWriter
import com.pdftron.pdf.PDFDoc
import com.pdftron.pdf.PageIterator
import com.pdftron.sdf.SDFDoc

class PDFDocMemoryTest : PDFNetSample() {
    override fun run(outputListener: OutputListener?) {
        super.run(outputListener)
        mOutputListener = outputListener
        mFileList.clear()
        printHeader(outputListener!!)

        // 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.
            val file = MappedFile(Utils.getAssetTempFile(INPUT_PATH.toString() + "tiger.pdf")!!.getAbsolutePath())
            val file_sz: Long = file.fileSize()
            val file_reader: com.pdftron.filters.FilterReader = com.pdftron.filters.FilterReader(file)
            val mem = ByteArray(file_sz.toInt())
            val bytes_read: Long = file_reader.read(mem)
            PDFDoc(mem).use { doc ->
                doc.initSecurityHandler()
                val num_pages: Int = doc.getPageCount()
                val writer = ElementWriter()
                val reader: com.pdftron.pdf.ElementReader = com.pdftron.pdf.ElementReader()
                var element: com.pdftron.pdf.Element?

                // Create a duplicate of every page but copy only path objects
                for (i in 1..num_pages) {
                    val itr: PageIterator = doc.getPageIterator(2 * i - 1)
                    val current: com.pdftron.pdf.Page? = itr.next()
                    reader.begin(current)
                    val new_page: com.pdftron.pdf.Page = doc.pageCreate(current!!.getMediaBox())
                    doc.pageInsert(itr, new_page)
                    writer.begin(new_page)
                    // Read page contents
                    while (true) {
                        element = reader.next()
                        if (element == null) {
                            break
                        }
                        //if (element.getType() == Element.e_path)
                        writer.writeElement(element)
                    }
                    writer.end()
                    reader.end()
                }
                doc.save(Utils.createExternalFile("doc_memory_edit.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.REMOVE_UNUSED, null)

                // Save the document to a memory buffer.
                val buf: ByteArray = 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
                run({
                    val outfile: java.io.File = java.io.File(Utils.createExternalFile("doc_memory_edit.txt", mFileList).getAbsolutePath())
                    val fop: java.io.FileOutputStream = java.io.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 (true) {
                    element = reader.next()
                    if (element == null) {
                        break
                    }
                    if (element.getType() == com.pdftron.pdf.Element.e_path) mOutputListener!!.print("Path, ")
                }
                reader.end()
                mOutputListener!!.println("\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...")
            }
        } catch (e: PDFNetException) {
            mOutputListener!!.printError(e.getStackTrace())
            mOutputListener!!.printError(e.getStackTrace())
        } catch (e: java.lang.Exception) {
            mOutputListener!!.printError(e.getStackTrace())
        }
        for (file in mFileList) {
            addToFileList(file)
        }
        printFooter(outputListener)
    }

    companion object {
        private var mOutputListener: OutputListener? = null
        private val mFileList: java.util.ArrayList<String> = java.util.ArrayList<String>()
    }

    init {
        setTitle(R.string.sample_pdfdocmemory_title)
        setDescription(R.string.sample_pdfdocmemory_description)
    }
}
```

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