> 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/pdfpackagetest.md).

# PDFPackage

Sample Java, Kotlin code for using Apryse Android SDK for creating, extracting, and manipulating PDF packages (also known as PDF portfolios).

Sample Java, Kotlin code for using Apryse Android SDK for creating, extracting, and manipulating PDF packages (also known as PDF portfolios).

Learn more about our full [PDF Data Extraction SDK Capabilities](https://apryse.com/capabilities/extraction).

To start your free trial, [get started with Android SDK](/android/get-started/get-started.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.Filter;
import com.pdftron.pdf.ColorPt;
import com.pdftron.pdf.ColorSpace;
import com.pdftron.pdf.Element;
import com.pdftron.pdf.ElementBuilder;
import com.pdftron.pdf.ElementWriter;
import com.pdftron.pdf.FileSpec;
import com.pdftron.pdf.Font;
import com.pdftron.pdf.PDFDoc;
import com.pdftron.pdf.Page;
import com.pdftron.pdf.Rect;
import com.pdftron.sdf.NameTree;
import com.pdftron.sdf.NameTreeIterator;
import com.pdftron.sdf.Obj;
import com.pdftron.sdf.SDFDoc;

import java.util.ArrayList;

//-----------------------------------------------------------------------------------
//This sample illustrates how to create, extract, and manipulate PDF Portfolios
//(a.k.a. PDF Packages) using PDFNet SDK.
//-----------------------------------------------------------------------------------

public class PDFPackageTest extends PDFNetSample {

	private static OutputListener mOutputListener;

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

    public PDFPackageTest() {
        setTitle(R.string.sample_pdfpackage_title);
        setDescription(R.string.sample_pdfpackage_description);
    }

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

        // Create a PDF Package.
        try (PDFDoc doc = new PDFDoc()) {
            
            addPackage(doc, Utils.getAssetTempFile(INPUT_PATH + "numbered.pdf").getAbsolutePath(), "My File 1");
            addPackage(doc, Utils.getAssetTempFile(INPUT_PATH + "newsletter.pdf").getAbsolutePath(), "My Newsletter...");
            addPackage(doc, Utils.getAssetTempFile(INPUT_PATH + "peppers.jpg").getAbsolutePath(), "An image");
            addCoverPage(doc);
            doc.save(Utils.createExternalFile("package.pdf", mFileList).getAbsolutePath(), SDFDoc.SaveMode.LINEARIZED, null);
            mOutputListener.println("Done.");			
        } catch (Exception e) {
            mOutputListener.printError(e.getStackTrace());
        }

        // Extract parts from a PDF Package.
        try (PDFDoc doc = new PDFDoc(Utils.createExternalFile("package.pdf", mFileList).getAbsolutePath())) {
            doc.initSecurityHandler();

            com.pdftron.sdf.NameTree files = NameTree.find(doc.getSDFDoc(), "EmbeddedFiles");
            if (files.isValid()) {
                // Traverse the list of embedded files.
                NameTreeIterator i = files.getIterator();
                for (int counter = 0; i.hasNext(); i.next(), ++counter) {
                    String entry_name = i.key().getAsPDFText();
                    mOutputListener.println("Part: " + entry_name);

                    FileSpec file_spec = new FileSpec(i.value());
                    Filter stm = file_spec.getFileData();
                    if (stm != null) {
                        String ext = "pdf";
                        if (entry_name.lastIndexOf('.') > 0) {
                            ext = entry_name.substring(entry_name.lastIndexOf('.')+1);
                        }
                        String fname = "extract_" + counter + "." + ext;
                        stm.writeToFile(Utils.createExternalFile(fname, mFileList).getAbsolutePath(), false);
                    }
                }
            }
            mOutputListener.println("Done.");
        } catch (Exception e) {
            mOutputListener.printError(e.getStackTrace());
        }

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

    static void addPackage(PDFDoc doc, String file, String desc) throws PDFNetException {
        NameTree files = NameTree.create(doc.getSDFDoc(), "EmbeddedFiles");
        FileSpec fs = FileSpec.create(doc, file, true);
        files.put(file.getBytes(), fs.getSDFObj());
        fs.getSDFObj().putText("Desc", desc);

        Obj collection = doc.getRoot().findObj("Collection");
        if (collection == null) collection = doc.getRoot().putDict("Collection");

        // You could here manipulate any entry in the Collection dictionary.
        // For example, the following line sets the tile mode for initial view mode
        // Please refer to section '2.3.5 Collections' in PDF Reference for details.
        collection.putName("View", "T");
    }

    static void addCoverPage(PDFDoc doc) throws PDFNetException {
        // Here we dynamically generate cover page (please see ElementBuilder
        // sample for more extensive coverage of PDF creation API).
        Page page = doc.pageCreate(new Rect(0, 0, 200, 200));

        ElementBuilder b = new ElementBuilder();
        ElementWriter w = new ElementWriter();
        w.begin(page);
        Font font = Font.create(doc.getSDFDoc(), Font.e_helvetica);
        w.writeElement(b.createTextBegin(font, 12));
        Element e = b.createTextRun("My PDF Collection");
        e.setTextMatrix(1, 0, 0, 1, 50, 96);
        e.getGState().setFillColorSpace(ColorSpace.createDeviceRGB());
        e.getGState().setFillColor(new ColorPt(1, 0, 0));
        w.writeElement(e);
        w.writeElement(b.createTextEnd());
        w.end();
        doc.pagePushBack(page);

        // Alternatively we could import a PDF page from a template PDF document
        // (for an example please see PDFPage sample project).
        // ...
    }

}
```

{% 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.pdf.*
import com.pdftron.sdf.NameTree
import com.pdftron.sdf.SDFDoc
import java.util.*

//-----------------------------------------------------------------------------------
//This sample illustrates how to create, extract, and manipulate PDF Portfolios
//(a.k.a. PDF Packages) using PDFNet SDK.
//-----------------------------------------------------------------------------------

class PDFPackageTest : PDFNetSample() {
    init {
        setTitle(R.string.sample_pdfpackage_title)
        setDescription(R.string.sample_pdfpackage_description)
    }

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

        // Create a PDF Package.

        // Create a PDF Package.
        try {
            PDFDoc().use { doc ->
                addPackage(doc, Utils.getAssetTempFile(INPUT_PATH + "numbered.pdf")!!.absolutePath, "My File 1")
                addPackage(doc, Utils.getAssetTempFile(INPUT_PATH + "newsletter.pdf")!!.absolutePath, "My Newsletter...")
                addPackage(doc, Utils.getAssetTempFile(INPUT_PATH + "peppers.jpg")!!.absolutePath, "An image")
                addCoverPage(doc)
                doc.save(Utils.createExternalFile("package.pdf", mFileList).absolutePath, SDFDoc.SaveMode.LINEARIZED, null)
                mOutputListener!!.println("Done.")
            }
        } catch (e: Exception) {
            mOutputListener!!.printError(e.stackTrace)
        }

        // Extract parts from a PDF Package.
        try {
            PDFDoc(Utils.createExternalFile("package.pdf", mFileList).absolutePath).use { doc ->
                doc.initSecurityHandler()
                val files = NameTree.find(doc.sdfDoc, "EmbeddedFiles")
                if (files.isValid) {
                    // Traverse the list of embedded files.
                    val i = files.iterator
                    var counter = 0
                    while (i.hasNext()) {
                        val entry_name = i.key().asPDFText
                        mOutputListener!!.println("Part: " + entry_name);
                        val file_spec = FileSpec(i.value())
                        val stm = file_spec.fileData
                        if (stm != null) {
                            var ext = "pdf"
                            if (entry_name.lastIndexOf('.') > 0) {
                                ext = entry_name.substring(entry_name.lastIndexOf('.') + 1)
                            }
                            val fname = "extract_$counter.$ext"
                            stm.writeToFile(Utils.createExternalFile(fname, PDFPackageTest.mFileList).absolutePath, false)
                        }
                        i.next()
                        ++counter
                    }
                }
                mOutputListener!!.println("Done.")
            }
        } catch (e: Exception) {
            mOutputListener!!.printError(e.stackTrace)
        }

        for (file in mFileList) {
            addToFileList(file!!)
        }
        printFooter(outputListener!!)
    }

    companion object {

        private var mOutputListener: OutputListener? = null

        private val mFileList = ArrayList<String>()

        @Throws(PDFNetException::class)
        fun addPackage(doc: PDFDoc, file: String, desc: String?) {
            val files = NameTree.create(doc.sdfDoc, "EmbeddedFiles")
            val fs = FileSpec.create(doc, file, true)
            files.put(file.toByteArray(), fs.sdfObj)
            fs.sdfObj.putText("Desc", desc)
            var collection = doc.root.findObj("Collection")
            if (collection == null) collection = doc.root.putDict("Collection")

            // You could here manipulate any entry in the Collection dictionary.
            // For example, the following line sets the tile mode for initial view mode
            // Please refer to section '2.3.5 Collections' in PDF Reference for details.
            collection!!.putName("View", "T")
        }

        @Throws(PDFNetException::class)
        fun addCoverPage(doc: PDFDoc) {
            // Here we dynamically generate cover page (please see ElementBuilder
            // sample for more extensive coverage of PDF creation API).
            val page = doc.pageCreate(Rect(0.0, 0.0, 200.0, 200.0))
            val b = ElementBuilder()
            val w = ElementWriter()
            w.begin(page)
            val font = Font.create(doc.sdfDoc, Font.e_helvetica)
            w.writeElement(b.createTextBegin(font, 12.0))
            val e = b.createTextRun("My PDF Collection")
            e.setTextMatrix(1.0, 0.0, 0.0, 1.0, 50.0, 96.0)
            e.gState.fillColorSpace = ColorSpace.createDeviceRGB()
            e.gState.fillColor = ColorPt(1.0, 0.0, 0.0)
            w.writeElement(e)
            w.writeElement(b.createTextEnd())
            w.end()
            doc.pagePushBack(page)

            // Alternatively we could import a PDF page from a template PDF document
            // (for an example please see PDFPage sample project).
            // ...
        }
    }

}
```

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