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

# Portfolio/PDF Packages - PDFPackage

Sample code to use Apryse SDK for creating, extracting, and manipulating PDF packages (PDF portfolios).  Sample code provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB.

Sample code to use Apryse SDK for creating, extracting, and manipulating PDF packages (also known as PDF portfolios). Sample code provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB.

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

To start your free trial, [get stated with 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 pdftron;
using pdftron.Common;
using pdftron.Filters;
using pdftron.SDF;
using pdftron.PDF;

namespace PackageTestCS
{
	/// <summary>
	/// This sample illustrates how to create, extract, and manipulate PDF Portfolios
	/// (a.k.a. PDF Packages) using PDFNet SDK.
	/// </summary>
	class Class1
	{
		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
		static Class1() {}
		
		// Relative path to the folder containing test files.
		const string input_path =  "../../../../TestFiles/";
		const string output_path = "../../../../TestFiles/Output/";

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			PDFNet.Initialize(PDFTronLicense.Key);

			// Create a PDF Package.
			try
			{
				using (PDFDoc doc = new PDFDoc())
				{
					AddPackage(doc, input_path + "numbered.pdf", "My File 1");
					AddPackage(doc, input_path + "newsletter.pdf", "My Newsletter...");
					AddPackage(doc, input_path + "peppers.jpg", "An image");
					AddCovePage(doc);
					doc.Save(output_path + "package.pdf", SDFDoc.SaveOptions.e_linearized);
					Console.WriteLine("Done.");
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}

			// Extract parts from a PDF Package.
			try
			{
				using (PDFDoc doc = new PDFDoc(output_path + "package.pdf"))
				{
					doc.InitSecurityHandler();

					pdftron.SDF.NameTree files = NameTree.Find(doc, "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();
							Console.WriteLine("Part: {0}", entry_name);
							FileSpec file_spec = new FileSpec(i.Value());
							Filter stm = file_spec.GetFileData();
							if (stm!=null) 
							{
								string fname = "extract_" + counter.ToString() + System.IO.Path.GetExtension(entry_name);
								stm.WriteToFile(output_path + fname, false);
							}
						}
					}
				}

				Console.WriteLine("Done.");
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}
			PDFNet.Terminate();
		}

		static void AddPackage(PDFDoc doc, string file, string desc) 
		{
			NameTree files = NameTree.Create(doc, "EmbeddedFiles");
			FileSpec fs = FileSpec.Create(doc, file, true);
			byte[] file1_name = System.Text.Encoding.UTF8.GetBytes(file);
			files.Put(file1_name, 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 AddCovePage(PDFDoc doc) 
		{
			// 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));

			using (ElementBuilder b = new ElementBuilder())
			using (ElementWriter w = new ElementWriter())
			{
				w.Begin(page); 
				Font font = Font.Create(doc, Font.StandardType1Font.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="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 <SDF/NameTree.h>
#include <PDF/PDFNet.h>
#include <PDF/PDFDoc.h>
#include <PDF/PDFDraw.h>
#include <PDF/ElementBuilder.h>
#include <PDF/ElementWriter.h>
#include <Filters/MappedFile.h>

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

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

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

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

static void AddPackage(PDFDoc& doc, string file, const char* desc) 
{
	NameTree files = NameTree::Create(doc, "EmbeddedFiles");
	FileSpec fs = FileSpec::Create(doc, file.c_str(), true);
	files.Put((UChar*)file.c_str(), int(file.size()), fs.GetSDFObj());
	fs.SetDesc(desc);

	Obj collection = doc.GetRoot().FindObj("Collection");
	if (!collection) 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) 
{
	// Here we dynamically generate cover page (please see ElementBuilder 
	// sample for more extensive coverage of PDF creation API).
	Page page = doc.PageCreate(Rect(0, 0, 200, 200));

	ElementBuilder b;
	ElementWriter w;
	w.Begin(page);
	Font font = Font::Create(doc, 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(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).
	// ...
}

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

	// Create a PDF Package.
	try
	{
		PDFDoc doc;
		AddPackage(doc, input_path + "numbered.pdf", "My File 1");
		AddPackage(doc, input_path + "newsletter.pdf", "My Newsletter...");
		AddPackage(doc, input_path + "peppers.jpg", "An image");
		AddCoverPage(doc);
		doc.Save((output_path + "package.pdf").c_str(), SDFDoc::e_linearized, 0);
		cout << "Done." << endl;
	}
	catch(Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch(...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	// Extract parts from a PDF Package.
	try  
	{	 
		PDFDoc doc((output_path + "package.pdf").c_str());
		doc.InitSecurityHandler();

		NameTree files = NameTree::Find(doc, "EmbeddedFiles");
		if(files.IsValid()) 
		{ 
			// Traverse the list of embedded files.
			NameTreeIterator i = files.GetIterator();
			for (int counter = 0; i.HasNext(); i.Next(), ++counter) 
			{
				UString entry_name;
				i.Key().GetAsPDFText(entry_name);
				cout << "Part: " << entry_name.ConvertToAscii() << endl;
				FileSpec file_spec(i.Value());
				Filter stm(file_spec.GetFileData());
				if (stm) 
				{
					string tmp = entry_name.ConvertToUtf8();
					string ext = tmp.find_last_of(".") != string::npos ? tmp.substr(tmp.find_last_of(".") + 1) : "pdf";
					char tmpbuf[1024];
					sprintf(tmpbuf, "%sextract_%d.%s", output_path.c_str(), counter, ext.c_str());
					stm.WriteToFile(UString(tmpbuf), false);
				}
			}
		}

		cout << "Done." << 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"
    "path/filepath"
    "strconv"
	. "pdftron"
)

import  "pdftron/Samples/LicenseKey/GO"

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

func AddPackage(doc PDFDoc, file string, desc string){
    files := NameTreeCreate(doc.GetSDFDoc(), "EmbeddedFiles")
    fs := FileSpecCreate(doc.GetSDFDoc(), file, true)
    key := make([]byte, len(file))
    for i := 0; i < len(file); i++{
        key[i] = file[i]
        //fmt.Println(file[i])
    }
    files.Put(&key[0], len(key), fs.GetSDFObj())
    fs.SetDesc(desc)
    
    collection := doc.GetRoot().FindObj("Collection")
    if collection.GetMp_obj().Swigcptr() == 0{
        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");
}

func AddCoverPage(doc PDFDoc){
    // Here we dynamically generate cover page (please see ElementBuilder 
    // sample for more extensive coverage of PDF creation API).
    page := doc.PageCreate(NewRect(0.0, 0.0, 200.0, 200.0))
    
    b := NewElementBuilder()
    w := NewElementWriter()
    
    w.Begin(page)
    font := FontCreate(doc.GetSDFDoc(), FontE_helvetica)
    w.WriteElement(b.CreateTextBegin(font, 12.0))
    e := b.CreateTextRun("My PDF Collection")
    e.SetTextMatrix(1.0, 0.0, 0.0, 1.0, 50.0, 96.0)
    e.GetGState().SetFillColorSpace(ColorSpaceCreateDeviceRGB())
    e.GetGState().SetFillColor(NewColorPt(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).
    // ...
}    

func main(){
    PDFNetInitialize(PDFTronLicense.Key)
    
    // Relative path to the folder containing the test files.
    inputPath := "../../TestFiles/"
    outputPath := "../../TestFiles/Output/"
    
    // Create a PDF Package.
    doc := NewPDFDoc()
    AddPackage(doc, inputPath + "numbered.pdf", "My File 1")
    AddPackage(doc, inputPath + "newsletter.pdf", "My Newsletter...")
    AddPackage(doc, inputPath + "peppers.jpg", "An image")
    AddCoverPage(doc)
    doc.Save(outputPath + "package.pdf", uint(SDFDocE_linearized))
    doc.Close()
    fmt.Println("Done.")
    
    // Extract parts from a PDF Package
    doc = NewPDFDoc(outputPath + "package.pdf")
    doc.InitSecurityHandler()
    
    files := NameTreeFind(doc.GetSDFDoc(), "EmbeddedFiles")
    if files.IsValid(){
        // Traverse the list of embedded files.
        i := files.GetIterator()
        counter := 0
        for i.HasNext(){
            entryName := i.Key().GetAsPDFText()
            fmt.Println("Part: " + entryName)
            fileSpec := NewFileSpec(i.Value())
            stm := NewFilter(fileSpec.GetFileData())
            if stm.GetM_impl().Swigcptr() != 0{
                stm.WriteToFile(outputPath + "extract_" + strconv.Itoa(counter) + filepath.Ext(entryName), false)
            }

            i.Next()
            counter = counter + 1
        }
    }
    doc.Close()
    PDFNetTerminate()
    fmt.Println("Done.")
}
```

{% 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 com.pdftron.common.PDFNetException;
import com.pdftron.pdf.*;
import com.pdftron.filters.*;
import com.pdftron.sdf.*;


//-----------------------------------------------------------------------------------
// This sample illustrates how to create, extract, and manipulate PDF Portfolios
// (a.k.a. PDF Packages) using PDFNet SDK.
//-----------------------------------------------------------------------------------
public class PDFPackageTest {
    // Relative path to the folder containing test files.
    static String input_path = "../../TestFiles/";
    static String output_path = "../../TestFiles/Output/";

    public static void main(String[] args) {
        PDFNet.initialize(PDFTronLicense.Key());

        // Create a PDF Package.
        try (PDFDoc doc = new PDFDoc()) {
            
            addPackage(doc, input_path + "numbered.pdf", "My File 1");
            addPackage(doc, input_path + "newsletter.pdf", "My Newsletter...");
            addPackage(doc, input_path + "peppers.jpg", "An image");
            addCoverPage(doc);
            doc.save(output_path + "package.pdf", SDFDoc.SaveMode.LINEARIZED, null);
            System.out.println("Done.");			
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Extract parts from a PDF Package.
        try (PDFDoc doc = new PDFDoc(output_path + "package.pdf")) {
            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();
                    System.out.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(output_path + fname, false);
                    }
                }
            }
            System.out.println("Done.");
        } catch (Exception e) {
            e.printStackTrace();
        }

        PDFNet.terminate();
    }

    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="JavaScript" %}
{% code lineNumbers="true" %}

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

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

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

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

  exports.runPDFPackageTest = () => {
    // Relative path to the folder containing test files.
    const inputPath = '../TestFiles/';
    const outputPath = inputPath + 'Output/';

    const addPackage = async (doc, file, desc) => {
      const files = await PDFNet.NameTree.create(doc, 'EmbeddedFiles');
      const fs = await PDFNet.FileSpec.create(doc, file, true);
      files.put(file, await fs.getSDFObj());
      fs.setDesc(desc);

      const root = await doc.getRoot();
      let collection = await root.findObj('Collection');
      if (!collection) collection = await 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');
    }

    const addCoverPage = async (doc) => {
      // Here we dynamically generate cover page (please see ElementBuilder 
      // sample for more extensive coverage of PDF creation API).
      const page = await doc.pageCreate(await PDFNet.Rect.init(0, 0, 200, 200));

      const b = await PDFNet.ElementBuilder.create();
      const w = await PDFNet.ElementWriter.create();
      w.beginOnPage(page);
      const font = await PDFNet.Font.create(doc, PDFNet.Font.StandardType1Font.e_helvetica);
      w.writeElement(await b.createTextBeginWithFont(font, 12));
      const e = await b.createNewTextRun('My PDF Collection');
      e.setTextMatrixEntries(1, 0, 0, 1, 50, 96);
      const gstate = await e.getGState();
      gstate.setFillColorSpace(await PDFNet.ColorSpace.createDeviceRGB());
      gstate.setFillColorWithColorPt(await PDFNet.ColorPt.init(1, 0, 0));
      w.writeElement(e);
      w.writeElement(await 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).
    }

    const main = async () => {

      // Create a PDF Package.
      try {
        const doc = await PDFNet.PDFDoc.create();
        await addPackage(doc, inputPath + 'numbered.pdf', 'My File 1');
        await addPackage(doc, inputPath + 'newsletter.pdf', 'My Newsletter...');
        await addPackage(doc, inputPath + 'peppers.jpg', 'An image');
        await addCoverPage(doc);
        await doc.save(outputPath + 'package.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
        console.log('Done.');
      } catch (err) {
        console.log(err);
      }

      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath(outputPath + 'package.pdf');
        await doc.initSecurityHandler();

        const files = await PDFNet.NameTree.find(doc, 'EmbeddedFiles');
        if (await files.isValid()) {
          // Traverse the list of embedded files.
          const i = await files.getIteratorBegin();
          for (var counter = 0; await i.hasNext(); await i.next(), ++counter) {
            const entry_name = await i.key().then(key => key.getAsPDFText());
            console.log('Part: ' + entry_name);
            const file_spec = await PDFNet.FileSpec.createFromObj(await i.value());
            const stm = await file_spec.getFileData();
            if (stm) {
              let ext = '.pdf';
              if (entry_name.includes('.')) {
                ext = entry_name.substr(entry_name.lastIndexOf('.'));
              }
              stm.writeToFile(outputPath + 'extract_' + counter + ext, false);
            }
          }
        }

        console.log('Done.');
      } 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.runPDFPackageTest();
})(exports);
  // eslint-disable-next-line spaced-comment
  //# sourceURL=PDFPackageTest.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 test files.
$input_path = getcwd()."/../../TestFiles/";
$output_path = $input_path."Output/";

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

function AddPackage($doc, $file, $desc) 
{
	$files = NameTree::Create($doc->GetSDFDoc(), "EmbeddedFiles");
	$fs = FileSpec::Create($doc->GetSDFDoc(), $file, true);
	$files->Put($file, strlen($file), $fs->GetSDFObj());
	$fs->SetDesc($desc);

	$collection = $doc->GetRoot()->FindObj("Collection");
	if (!$collection) $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");
}

function AddCoverPage($doc) 
{
	// Here we dynamically generate cover page (please see ElementBuilder 
	// sample for more extensive coverage of PDF creation API).
	$page = $doc->PageCreate(new Rect(0.0, 0.0, 200.0, 200.0));

	$builder = new ElementBuilder();
	$writer = new ElementWriter();
	$writer->Begin($page);
	$font = Font::Create($doc->GetSDFDoc(), Font::e_helvetica);
	$writer->WriteElement($builder->CreateTextBegin($font, 12.0));
	$element = $builder->CreateTextRun("My PDF Collection");
	$element->SetTextMatrix(1.0, 0.0, 0.0, 1.0, 50.0, 96.0);
	$element->GetGState()->SetFillColorSpace(ColorSpace::CreateDeviceRGB());
	$element->GetGState()->SetFillColor(new ColorPt(1.0, 0.0, 0.0));
	$writer->WriteElement($element);
	$writer->WriteElement($builder->CreateTextEnd());
	$writer->End();
	$doc->PagePushBack($page);

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

//---------------------------------------------------------------------------------------

	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.

	// Create a PDF Package.
	
	$doc = new PDFDoc();
	AddPackage($doc, $input_path."numbered.pdf", "My File 1");
	AddPackage($doc, $input_path."newsletter.pdf", "My Newsletter...");
	AddPackage($doc, $input_path."peppers.jpg", "An image");
	AddCoverPage($doc);
	$doc->Save($output_path."package.pdf", SDFDoc::e_linearized);
	$doc->Close();
	echo nl2br("Done.\n");

	// Extract parts from a PDF Package.
	
	$doc = new PDFDoc($output_path."package.pdf");
	$doc->InitSecurityHandler();

	$files = NameTree::Find($doc->GetSDFDoc(), "EmbeddedFiles");
	if($files->IsValid()) 
	{ 
		// Traverse the list of embedded files.
		$i = $files->GetIterator();
		for ($counter = 0; $i->HasNext(); $i->Next(), ++$counter) 
		{
			$entry_name = $i->Key()->GetAsPDFText();
			echo nl2br("Part: ".$entry_name."\n");
			$file_spec = new FileSpec($i->Value());
			$stm = new Filter($file_spec->GetFileData());
			if ($stm) 
			{
				$stm->WriteToFile($output_path."extract_".$counter.".".pathinfo($entry_name, PATHINFO_EXTENSION), false);
			}
		}
	}

	$doc->Close();
	PDFNet::Terminate();
	echo nl2br("Done.\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, os
from PDFNetPython import *

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

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

def AddPackage(doc, file, desc):
    files = NameTree.Create(doc.GetSDFDoc(), "EmbeddedFiles")
    fs = FileSpec.Create(doc.GetSDFDoc(), file, True)
    key = bytearray(file, "utf-8")
    files.Put(key, len(key), fs.GetSDFObj())
    fs.SetDesc(desc)
    
    collection = doc.GetRoot().FindObj("Collection")
    if collection is None:
        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");
    
def AddCoverPage(doc):
    # Here we dynamically generate cover page (please see ElementBuilder 
    # sample for more extensive coverage of PDF creation API).
    page = doc.PageCreate(Rect(0, 0, 200, 200))
    
    b = ElementBuilder()
    w = ElementWriter()
    
    w.Begin(page)
    font = Font.Create(doc.GetSDFDoc(), Font.e_helvetica)
    w.WriteElement(b.CreateTextBegin(font, 12))
    e = b.CreateTextRun("My PDF Collection")
    e.SetTextMatrix(1, 0, 0, 1, 50, 96)
    e.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB())
    e.GetGState().SetFillColor(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).
    # ...
    

def main():
    PDFNet.Initialize(LicenseKey)
    
    # Relative path to the folder containing the test files.
    input_path = "../../TestFiles/"
    output_path = "../../TestFiles/Output/"
    
    # Create a PDF Package.
    doc =PDFDoc()
    AddPackage(doc, input_path + "numbered.pdf", "My File 1")
    AddPackage(doc, input_path + "newsletter.pdf", "My Newsletter...")
    AddPackage(doc, input_path + "peppers.jpg", "An image")
    AddCoverPage(doc)
    doc.Save(output_path + "package.pdf", SDFDoc.e_linearized)
    doc.Close()
    print("Done.")
    
    # Extract parts from a PDF Package
    doc = PDFDoc(output_path + "package.pdf")
    doc.InitSecurityHandler()
    
    files = NameTree.Find(doc.GetSDFDoc(), "EmbeddedFiles")
    if files.IsValid():
        # Traverse the list of embedded files.
        i = files.GetIterator()
        counter = 0
        while i.HasNext():
            entry_name = i.Key().GetAsPDFText()
            print("Part: " + entry_name)
            file_spec = FileSpec(i.Value())
            stm = Filter(file_spec.GetFileData())
            if stm != None:
                stm.WriteToFile(output_path + "extract_" + str(counter) + os.path.splitext(entry_name)[1], False)
            
            i.Next()
            counter = counter + 1
    doc.Close()
    PDFNet.Terminate()
    print("Done.")

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

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

def AddPackage(doc, file, desc)
	files = NameTree.Create(doc.GetSDFDoc, "EmbeddedFiles")
	fs = FileSpec.Create(doc.GetSDFDoc, file, true)
	files.Put(file, file.length, fs.GetSDFObj)
	fs.SetDesc(desc)
	
	collection = doc.GetRoot.FindObj("Collection")
	if collection.nil?
		collection = doc.GetRoot.PutDict("Collection")
	end
	
	# 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")
end
	
def AddCoverPage(doc)
	# Here we dynamically generate cover page (please see ElementBuilder 
	# sample for more extensive coverage of PDF creation API).
	page = doc.PageCreate(Rect.new(0, 0, 200, 200))
	
	b = ElementBuilder.new
	w = ElementWriter.new
	
	w.Begin(page)
	font = Font.Create(doc.GetSDFDoc, Font::E_helvetica)
	w.WriteElement(b.CreateTextBegin(font, 12))
	e = b.CreateTextRun("My PDF Collection")
	e.SetTextMatrix(1, 0, 0, 1, 50, 96)
	e.GetGState.SetFillColorSpace(ColorSpace.CreateDeviceRGB)
	e.GetGState.SetFillColor(ColorPt.new(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).
	# ...
end
	
	PDFNet.Initialize(PDFTronLicense.Key)
	
	# Relative path to the folder containing the test files.
	input_path = "../../TestFiles/"
	output_path = "../../TestFiles/Output/"
	
	# Create a PDF Package.
	doc = PDFDoc.new
	AddPackage(doc, input_path + "numbered.pdf", "My File 1")
	AddPackage(doc, input_path + "newsletter.pdf", "My Newsletter...")
	AddPackage(doc, input_path + "peppers.jpg", "An image")
	AddCoverPage(doc)
	doc.Save(output_path + "package.pdf", SDFDoc::E_linearized)
	doc.Close
	puts "Done."
	
	# Extract parts from a PDF Package
	doc = PDFDoc.new(output_path + "package.pdf")
	doc.InitSecurityHandler
	
	files = NameTree.Find(doc.GetSDFDoc, "EmbeddedFiles")
	if files.IsValid
		# Traverse the list of embedded files.
		i = files.GetIterator
		counter = 0
		while i.HasNext do
			entry_name = i.Key.GetAsPDFText
			puts "Part: " + entry_name
			file_spec = FileSpec.new(i.Value)
			stm = Filter.new(file_spec.GetFileData)
			if !stm.nil?
				stm.WriteToFile(output_path + "extract_" + counter.to_s + File.extname(entry_name), false)
			end
			i.Next
			counter = counter + 1
		end
	end
	doc.Close
	PDFNet.Terminate
	puts "Done."
```

{% endcode %}
{% endtab %}

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

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

Imports System

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

Module PackageTestVB
    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

            Using doc As PDFDoc = New PDFDoc
                AddPackage(doc, input_path & "numbered.pdf", "My File 1")
                AddPackage(doc, input_path & "newsletter.pdf", "My Newsletter...")
                AddPackage(doc, input_path & "peppers.jpg", "An image")
                AddCovePage(doc)
                doc.Save(output_path & "package.pdf", SDFDoc.SaveOptions.e_linearized)
                Console.WriteLine("Done.")
            End Using

        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try

        Try

            Using doc As PDFDoc = New PDFDoc(output_path & "package.pdf")
                doc.InitSecurityHandler()
                Dim files As pdftron.SDF.NameTree = NameTree.Find(doc, "EmbeddedFiles")

                If files.IsValid() Then
                    ' Traverse the list of embedded files.
                    Dim i As NameTreeIterator = files.GetIterator()
                    Dim counter As Integer = 0

                    While i.HasNext()
                        Dim entry_name As String = i.Key().GetAsPDFText()
                        Console.WriteLine("Part: {0}", entry_name)
                        Dim file_spec As FileSpec = New FileSpec(i.Value())
                        Dim stm As Filter = file_spec.GetFileData()

                        If stm IsNot Nothing Then
                            Dim fname As String = output_path & "extract_" & counter.ToString() & System.IO.Path.GetExtension(entry_name)
                            stm.WriteToFile(fname, False)
                        End If

                        i.Next()
                        counter += 1
                    End While
                End If
            End Using

            Console.WriteLine("Done.")
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try
        PDFNet.Terminate()
    End Sub

    Private Sub AddPackage(ByVal doc As PDFDoc, ByVal file As String, ByVal desc As String)
        Dim files As NameTree = NameTree.Create(doc, "EmbeddedFiles")
        Dim fs As FileSpec = FileSpec.Create(doc, file, True)
        Dim file1_name As Byte() = System.Text.Encoding.UTF8.GetBytes(file)
        files.Put(file1_name, fs.GetSDFObj())
        fs.GetSDFObj().PutText("Desc", desc)
        Dim collection As Obj = doc.GetRoot().FindObj("Collection")
        If collection Is Nothing Then 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")
    End Sub

    Private Sub AddCovePage(ByVal doc As PDFDoc)
    ' Here we dynamically generate cover page (please see ElementBuilder 
    ' sample for more extensive coverage of PDF creation API).
        Dim page As Page = doc.PageCreate(New Rect(0, 0, 200, 200))

        Using b As ElementBuilder = New ElementBuilder()

            Using w As ElementWriter = New ElementWriter()
                w.Begin(page)
                Dim font As Font = Font.Create(doc, Font.StandardType1Font.e_helvetica)
                w.WriteElement(b.CreateTextBegin(font, 12))
                Dim e As Element = 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)
            End Using
        End Using
    ' Alternatively we could import a PDF page from a template PDF document
    ' (for an example please see PDFPage sample project).
    ' ...
    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/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.
