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.
To start your free trial, get stated with Server SDK.
1//
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3//
4using System;
5using pdftron;
6using pdftron.Common;
7using pdftron.Filters;
8using pdftron.SDF;
9using pdftron.PDF;
10
11namespace PackageTestCS
12{
13	/// <summary>
14	/// This sample illustrates how to create, extract, and manipulate PDF Portfolios
15	/// (a.k.a. PDF Packages) using PDFNet SDK.
16	/// </summary>
17	class Class1
18	{
19		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
20		static Class1() {}
21		
22		// Relative path to the folder containing test files.
23		const string input_path =  "../../../../TestFiles/";
24		const string output_path = "../../../../TestFiles/Output/";
25
26		/// <summary>
27		/// The main entry point for the application.
28		/// </summary>
29		[STAThread]
30		static void Main(string[] args)
31		{
32			PDFNet.Initialize(PDFTronLicense.Key);
33
34			// Create a PDF Package.
35			try
36			{
37				using (PDFDoc doc = new PDFDoc())
38				{
39					AddPackage(doc, input_path + "numbered.pdf", "My File 1");
40					AddPackage(doc, input_path + "newsletter.pdf", "My Newsletter...");
41					AddPackage(doc, input_path + "peppers.jpg", "An image");
42					AddCovePage(doc);
43					doc.Save(output_path + "package.pdf", SDFDoc.SaveOptions.e_linearized);
44					Console.WriteLine("Done.");
45				}
46			}
47			catch (PDFNetException e)
48			{
49				Console.WriteLine(e.Message);
50			}
51
52			// Extract parts from a PDF Package.
53			try
54			{
55				using (PDFDoc doc = new PDFDoc(output_path + "package.pdf"))
56				{
57					doc.InitSecurityHandler();
58
59					pdftron.SDF.NameTree files = NameTree.Find(doc, "EmbeddedFiles");
60					if(files.IsValid()) 
61					{ 
62						// Traverse the list of embedded files.
63						NameTreeIterator i = files.GetIterator();
64						for (int counter = 0; i.HasNext(); i.Next(), ++counter) 
65						{
66							string entry_name = i.Key().GetAsPDFText();
67							Console.WriteLine("Part: {0}", entry_name);
68							FileSpec file_spec = new FileSpec(i.Value());
69							Filter stm = file_spec.GetFileData();
70							if (stm!=null) 
71							{
72								string fname = "extract_" + counter.ToString() + System.IO.Path.GetExtension(entry_name);
73								stm.WriteToFile(output_path + fname, false);
74							}
75						}
76					}
77				}
78
79				Console.WriteLine("Done.");
80			}
81			catch (PDFNetException e)
82			{
83				Console.WriteLine(e.Message);
84			}
85			PDFNet.Terminate();
86		}
87
88		static void AddPackage(PDFDoc doc, string file, string desc) 
89		{
90			NameTree files = NameTree.Create(doc, "EmbeddedFiles");
91			FileSpec fs = FileSpec.Create(doc, file, true);
92			byte[] file1_name = System.Text.Encoding.UTF8.GetBytes(file);
93			files.Put(file1_name, fs.GetSDFObj());
94			fs.GetSDFObj().PutText("Desc", desc);
95
96			Obj collection = doc.GetRoot().FindObj("Collection");
97			if (collection == null) collection = doc.GetRoot().PutDict("Collection");
98
99			// You could here manipulate any entry in the Collection dictionary. 
100			// For example, the following line sets the tile mode for initial view mode
101			// Please refer to section '2.3.5 Collections' in PDF Reference for details.
102			collection.PutName("View", "T");
103		}
104
105		static void AddCovePage(PDFDoc doc) 
106		{
107			// Here we dynamically generate cover page (please see ElementBuilder 
108			// sample for more extensive coverage of PDF creation API).
109			Page page = doc.PageCreate(new Rect(0, 0, 200, 200));
110
111			using (ElementBuilder b = new ElementBuilder())
112			using (ElementWriter w = new ElementWriter())
113			{
114				w.Begin(page); 
115				Font font = Font.Create(doc, Font.StandardType1Font.e_helvetica);
116				w.WriteElement(b.CreateTextBegin(font, 12));
117				Element e = b.CreateTextRun("My PDF Collection");
118				e.SetTextMatrix(1, 0, 0, 1, 50, 96);
119				e.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB());
120				e.GetGState().SetFillColor(new ColorPt(1, 0, 0));
121				w.WriteElement(e);
122				w.WriteElement(b.CreateTextEnd());
123				w.End();
124				doc.PagePushBack(page);
125			}
126
127			// Alternatively we could import a PDF page from a template PDF document
128			// (for an example please see PDFPage sample project).
129			// ...
130		}
131	}
132}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6#include <SDF/NameTree.h>
7#include <PDF/PDFNet.h>
8#include <PDF/PDFDoc.h>
9#include <PDF/PDFDraw.h>
10#include <PDF/ElementBuilder.h>
11#include <PDF/ElementWriter.h>
12#include <Filters/MappedFile.h>
13
14#include <iostream>
15#include "../../LicenseKey/CPP/LicenseKey.h"
16
17using namespace pdftron;
18using namespace Common;
19using namespace Filters;
20using namespace SDF;
21using namespace PDF;
22using namespace std;
23
24//-----------------------------------------------------------------------------------
25/// This sample illustrates how to create, extract, and manipulate PDF Portfolios
26/// (a.k.a. PDF Packages) using PDFNet SDK.
27//-----------------------------------------------------------------------------------
28
29// Relative path to the folder containing test files.
30static const string input_path =  "../../TestFiles/";
31static const string output_path = "../../TestFiles/Output/";
32
33static void AddPackage(PDFDoc& doc, string file, const char* desc) 
34{
35	NameTree files = NameTree::Create(doc, "EmbeddedFiles");
36	FileSpec fs = FileSpec::Create(doc, file.c_str(), true);
37	files.Put((UChar*)file.c_str(), int(file.size()), fs.GetSDFObj());
38	fs.SetDesc(desc);
39
40	Obj collection = doc.GetRoot().FindObj("Collection");
41	if (!collection) collection = doc.GetRoot().PutDict("Collection");
42
43	// You could here manipulate any entry in the Collection dictionary. 
44	// For example, the following line sets the tile mode for initial view mode
45	// Please refer to section '2.3.5 Collections' in PDF Reference for details.
46	collection.PutName("View", "T");
47}
48
49static void AddCoverPage(PDFDoc& doc) 
50{
51	// Here we dynamically generate cover page (please see ElementBuilder 
52	// sample for more extensive coverage of PDF creation API).
53	Page page = doc.PageCreate(Rect(0, 0, 200, 200));
54
55	ElementBuilder b;
56	ElementWriter w;
57	w.Begin(page);
58	Font font = Font::Create(doc, Font::e_helvetica);
59	w.WriteElement(b.CreateTextBegin(font, 12));
60	Element e = b.CreateTextRun("My PDF Collection");
61	e.SetTextMatrix(1, 0, 0, 1, 50, 96);
62	e.GetGState().SetFillColorSpace(ColorSpace::CreateDeviceRGB());
63	e.GetGState().SetFillColor(ColorPt(1, 0, 0));
64	w.WriteElement(e);
65	w.WriteElement(b.CreateTextEnd());
66	w.End();
67	doc.PagePushBack(page);
68
69	// Alternatively we could import a PDF page from a template PDF document
70	// (for an example please see PDFPage sample project).
71	// ...
72}
73
74int main(int argc, char *argv[])
75{
76	int ret = 0;
77	PDFNet::Initialize(LicenseKey);
78
79	// Create a PDF Package.
80	try
81	{
82		PDFDoc doc;
83		AddPackage(doc, input_path + "numbered.pdf", "My File 1");
84		AddPackage(doc, input_path + "newsletter.pdf", "My Newsletter...");
85		AddPackage(doc, input_path + "peppers.jpg", "An image");
86		AddCoverPage(doc);
87		doc.Save((output_path + "package.pdf").c_str(), SDFDoc::e_linearized, 0);
88		cout << "Done." << endl;
89	}
90	catch(Common::Exception& e)
91	{
92		cout << e << endl;
93		ret = 1;
94	}
95	catch(...)
96	{
97		cout << "Unknown Exception" << endl;
98		ret = 1;
99	}
100
101	// Extract parts from a PDF Package.
102	try  
103	{	 
104		PDFDoc doc((output_path + "package.pdf").c_str());
105		doc.InitSecurityHandler();
106
107		NameTree files = NameTree::Find(doc, "EmbeddedFiles");
108		if(files.IsValid()) 
109		{ 
110			// Traverse the list of embedded files.
111			NameTreeIterator i = files.GetIterator();
112			for (int counter = 0; i.HasNext(); i.Next(), ++counter) 
113			{
114				UString entry_name;
115				i.Key().GetAsPDFText(entry_name);
116				cout << "Part: " << entry_name.ConvertToAscii() << endl;
117				FileSpec file_spec(i.Value());
118				Filter stm(file_spec.GetFileData());
119				if (stm) 
120				{
121					string tmp = entry_name.ConvertToUtf8();
122					string ext = tmp.find_last_of(".") != string::npos ? tmp.substr(tmp.find_last_of(".") + 1) : "pdf";
123					char tmpbuf[1024];
124					sprintf(tmpbuf, "%sextract_%d.%s", output_path.c_str(), counter, ext.c_str());
125					stm.WriteToFile(UString(tmpbuf), false);
126				}
127			}
128		}
129
130		cout << "Done." << endl;
131	}
132	catch(Common::Exception& e)
133	{
134		cout << e << endl;
135		ret = 1;
136	}
137	catch(...)
138	{
139		cout << "Unknown Exception" << endl;
140		ret = 1;
141	}
142
143	PDFNet::Terminate();
144	return ret;
145}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
3// Consult LICENSE.txt regarding license information.
4//---------------------------------------------------------------------------------------
5
6package main
7import (
8	"fmt"
9    "path/filepath"
10    "strconv"
11	. "pdftron"
12)
13
14import  "pdftron/Samples/LicenseKey/GO"
15
16//-----------------------------------------------------------------------------------
17// This sample illustrates how to create, extract, and manipulate PDF Portfolios
18// (a.k.a. PDF Packages) using PDFNet SDK.
19//-----------------------------------------------------------------------------------
20
21func AddPackage(doc PDFDoc, file string, desc string){
22    files := NameTreeCreate(doc.GetSDFDoc(), "EmbeddedFiles")
23    fs := FileSpecCreate(doc.GetSDFDoc(), file, true)
24    key := make([]byte, len(file))
25    for i := 0; i < len(file); i++{
26        key[i] = file[i]
27        //fmt.Println(file[i])
28    }
29    files.Put(&key[0], len(key), fs.GetSDFObj())
30    fs.SetDesc(desc)
31    
32    collection := doc.GetRoot().FindObj("Collection")
33    if collection.GetMp_obj().Swigcptr() == 0{
34        collection = doc.GetRoot().PutDict("Collection")
35    }
36
37    // You could here manipulate any entry in the Collection dictionary. 
38    // For example, the following line sets the tile mode for initial view mode
39    // Please refer to section '2.3.5 Collections' in PDF Reference for details.
40    collection.PutName("View", "T");
41}
42
43func AddCoverPage(doc PDFDoc){
44    // Here we dynamically generate cover page (please see ElementBuilder 
45    // sample for more extensive coverage of PDF creation API).
46    page := doc.PageCreate(NewRect(0.0, 0.0, 200.0, 200.0))
47    
48    b := NewElementBuilder()
49    w := NewElementWriter()
50    
51    w.Begin(page)
52    font := FontCreate(doc.GetSDFDoc(), FontE_helvetica)
53    w.WriteElement(b.CreateTextBegin(font, 12.0))
54    e := b.CreateTextRun("My PDF Collection")
55    e.SetTextMatrix(1.0, 0.0, 0.0, 1.0, 50.0, 96.0)
56    e.GetGState().SetFillColorSpace(ColorSpaceCreateDeviceRGB())
57    e.GetGState().SetFillColor(NewColorPt(1.0, 0.0, 0.0))
58    w.WriteElement(e)
59    w.WriteElement(b.CreateTextEnd())
60    w.End()
61    doc.PagePushBack(page)
62    
63    // Alternatively we could import a PDF page from a template PDF document
64    // (for an example please see PDFPage sample project).
65    // ...
66}    
67
68func main(){
69    PDFNetInitialize(PDFTronLicense.Key)
70    
71    // Relative path to the folder containing the test files.
72    inputPath := "../../TestFiles/"
73    outputPath := "../../TestFiles/Output/"
74    
75    // Create a PDF Package.
76    doc := NewPDFDoc()
77    AddPackage(doc, inputPath + "numbered.pdf", "My File 1")
78    AddPackage(doc, inputPath + "newsletter.pdf", "My Newsletter...")
79    AddPackage(doc, inputPath + "peppers.jpg", "An image")
80    AddCoverPage(doc)
81    doc.Save(outputPath + "package.pdf", uint(SDFDocE_linearized))
82    doc.Close()
83    fmt.Println("Done.")
84    
85    // Extract parts from a PDF Package
86    doc = NewPDFDoc(outputPath + "package.pdf")
87    doc.InitSecurityHandler()
88    
89    files := NameTreeFind(doc.GetSDFDoc(), "EmbeddedFiles")
90    if files.IsValid(){
91        // Traverse the list of embedded files.
92        i := files.GetIterator()
93        counter := 0
94        for i.HasNext(){
95            entryName := i.Key().GetAsPDFText()
96            fmt.Println("Part: " + entryName)
97            fileSpec := NewFileSpec(i.Value())
98            stm := NewFilter(fileSpec.GetFileData())
99            if stm.GetM_impl().Swigcptr() != 0{
100                stm.WriteToFile(outputPath + "extract_" + strconv.Itoa(counter) + filepath.Ext(entryName), false)
101            }
102
103            i.Next()
104            counter = counter + 1
105        }
106    }
107    doc.Close()
108    PDFNetTerminate()
109    fmt.Println("Done.")
110}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6import com.pdftron.common.PDFNetException;
7import com.pdftron.pdf.*;
8import com.pdftron.filters.*;
9import com.pdftron.sdf.*;
10
11
12//-----------------------------------------------------------------------------------
13// This sample illustrates how to create, extract, and manipulate PDF Portfolios
14// (a.k.a. PDF Packages) using PDFNet SDK.
15//-----------------------------------------------------------------------------------
16public class PDFPackageTest {
17    // Relative path to the folder containing test files.
18    static String input_path = "../../TestFiles/";
19    static String output_path = "../../TestFiles/Output/";
20
21    public static void main(String[] args) {
22        PDFNet.initialize(PDFTronLicense.Key());
23
24        // Create a PDF Package.
25        try (PDFDoc doc = new PDFDoc()) {
26            
27            addPackage(doc, input_path + "numbered.pdf", "My File 1");
28            addPackage(doc, input_path + "newsletter.pdf", "My Newsletter...");
29            addPackage(doc, input_path + "peppers.jpg", "An image");
30            addCoverPage(doc);
31            doc.save(output_path + "package.pdf", SDFDoc.SaveMode.LINEARIZED, null);
32            System.out.println("Done.");			
33        } catch (Exception e) {
34            e.printStackTrace();
35        }
36
37        // Extract parts from a PDF Package.
38        try (PDFDoc doc = new PDFDoc(output_path + "package.pdf")) {
39            doc.initSecurityHandler();
40
41            com.pdftron.sdf.NameTree files = NameTree.find(doc.getSDFDoc(), "EmbeddedFiles");
42            if (files.isValid()) {
43                // Traverse the list of embedded files.
44                NameTreeIterator i = files.getIterator();
45                for (int counter = 0; i.hasNext(); i.next(), ++counter) {
46                    String entry_name = i.key().getAsPDFText();
47                    System.out.println("Part: " + entry_name);
48
49                    FileSpec file_spec = new FileSpec(i.value());
50                    Filter stm = file_spec.getFileData();
51                    if (stm != null) {
52                        String ext = "pdf";
53                        if (entry_name.lastIndexOf('.') > 0) {
54                            ext = entry_name.substring(entry_name.lastIndexOf('.')+1);
55                        }
56                        String fname = "extract_" + counter + "." + ext;
57                        stm.writeToFile(output_path + fname, false);
58                    }
59                }
60            }
61            System.out.println("Done.");
62        } catch (Exception e) {
63            e.printStackTrace();
64        }
65
66        PDFNet.terminate();
67    }
68
69    static void addPackage(PDFDoc doc, String file, String desc) throws PDFNetException {
70        NameTree files = NameTree.create(doc.getSDFDoc(), "EmbeddedFiles");
71        FileSpec fs = FileSpec.create(doc, file, true);
72        files.put(file.getBytes(), fs.getSDFObj());
73        fs.getSDFObj().putText("Desc", desc);
74
75        Obj collection = doc.getRoot().findObj("Collection");
76        if (collection == null) collection = doc.getRoot().putDict("Collection");
77
78        // You could here manipulate any entry in the Collection dictionary.
79        // For example, the following line sets the tile mode for initial view mode
80        // Please refer to section '2.3.5 Collections' in PDF Reference for details.
81        collection.putName("View", "T");
82    }
83
84    static void addCoverPage(PDFDoc doc) throws PDFNetException {
85        // Here we dynamically generate cover page (please see ElementBuilder
86        // sample for more extensive coverage of PDF creation API).
87        Page page = doc.pageCreate(new Rect(0, 0, 200, 200));
88
89        ElementBuilder b = new ElementBuilder();
90        ElementWriter w = new ElementWriter();
91        w.begin(page);
92        Font font = Font.create(doc.getSDFDoc(), Font.e_helvetica);
93        w.writeElement(b.createTextBegin(font, 12));
94        Element e = b.createTextRun("My PDF Collection");
95        e.setTextMatrix(1, 0, 0, 1, 50, 96);
96        e.getGState().setFillColorSpace(ColorSpace.createDeviceRGB());
97        e.getGState().setFillColor(new ColorPt(1, 0, 0));
98        w.writeElement(e);
99        w.writeElement(b.createTextEnd());
100        w.end();
101        doc.pagePushBack(page);
102
103        // Alternatively we could import a PDF page from a template PDF document
104        // (for an example please see PDFPage sample project).
105        // ...
106    }
107}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6//-----------------------------------------------------------------------------------
7/// This sample illustrates how to create, extract, and manipulate PDF Portfolios
8/// (a.k.a. PDF Packages) using PDFNet SDK.
9//-----------------------------------------------------------------------------------
10
11const { PDFNet } = require('@pdftron/pdfnet-node');
12const PDFTronLicense = require('../LicenseKey/LicenseKey');
13
14((exports) => {
15  'use strict';
16
17  exports.runPDFPackageTest = () => {
18    // Relative path to the folder containing test files.
19    const inputPath = '../TestFiles/';
20    const outputPath = inputPath + 'Output/';
21
22    const addPackage = async (doc, file, desc) => {
23      const files = await PDFNet.NameTree.create(doc, 'EmbeddedFiles');
24      const fs = await PDFNet.FileSpec.create(doc, file, true);
25      files.put(file, await fs.getSDFObj());
26      fs.setDesc(desc);
27
28      const root = await doc.getRoot();
29      let collection = await root.findObj('Collection');
30      if (!collection) collection = await root.putDict('Collection');
31
32      // You could here manipulate any entry in the Collection dictionary. 
33      // For example, the following line sets the tile mode for initial view mode
34      // Please refer to section '2.3.5 Collections' in PDF Reference for details.
35      collection.putName('View', 'T');
36    }
37
38    const addCoverPage = async (doc) => {
39      // Here we dynamically generate cover page (please see ElementBuilder 
40      // sample for more extensive coverage of PDF creation API).
41      const page = await doc.pageCreate(await PDFNet.Rect.init(0, 0, 200, 200));
42
43      const b = await PDFNet.ElementBuilder.create();
44      const w = await PDFNet.ElementWriter.create();
45      w.beginOnPage(page);
46      const font = await PDFNet.Font.create(doc, PDFNet.Font.StandardType1Font.e_helvetica);
47      w.writeElement(await b.createTextBeginWithFont(font, 12));
48      const e = await b.createNewTextRun('My PDF Collection');
49      e.setTextMatrixEntries(1, 0, 0, 1, 50, 96);
50      const gstate = await e.getGState();
51      gstate.setFillColorSpace(await PDFNet.ColorSpace.createDeviceRGB());
52      gstate.setFillColorWithColorPt(await PDFNet.ColorPt.init(1, 0, 0));
53      w.writeElement(e);
54      w.writeElement(await b.createTextEnd());
55      w.end();
56      doc.pagePushBack(page);
57
58      // Alternatively we could import a PDF page from a template PDF document
59      // (for an example please see PDFPage sample project).
60    }
61
62    const main = async () => {
63
64      // Create a PDF Package.
65      try {
66        const doc = await PDFNet.PDFDoc.create();
67        await addPackage(doc, inputPath + 'numbered.pdf', 'My File 1');
68        await addPackage(doc, inputPath + 'newsletter.pdf', 'My Newsletter...');
69        await addPackage(doc, inputPath + 'peppers.jpg', 'An image');
70        await addCoverPage(doc);
71        await doc.save(outputPath + 'package.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
72        console.log('Done.');
73      } catch (err) {
74        console.log(err);
75      }
76
77      try {
78        const doc = await PDFNet.PDFDoc.createFromFilePath(outputPath + 'package.pdf');
79        await doc.initSecurityHandler();
80
81        const files = await PDFNet.NameTree.find(doc, 'EmbeddedFiles');
82        if (await files.isValid()) {
83          // Traverse the list of embedded files.
84          const i = await files.getIteratorBegin();
85          for (var counter = 0; await i.hasNext(); await i.next(), ++counter) {
86            const entry_name = await i.key().then(key => key.getAsPDFText());
87            console.log('Part: ' + entry_name);
88            const file_spec = await PDFNet.FileSpec.createFromObj(await i.value());
89            const stm = await file_spec.getFileData();
90            if (stm) {
91              let ext = '.pdf';
92              if (entry_name.includes('.')) {
93                ext = entry_name.substr(entry_name.lastIndexOf('.'));
94              }
95              stm.writeToFile(outputPath + 'extract_' + counter + ext, false);
96            }
97          }
98        }
99
100        console.log('Done.');
101      } catch (err) {
102        console.log(err);
103      }
104    }
105    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error) {
106      console.log('Error: ' + JSON.stringify(error));
107    }).then(function(){ return PDFNet.shutdown(); });
108  };
109  exports.runPDFPackageTest();
110})(exports);
111  // eslint-disable-next-line spaced-comment
112  //# sourceURL=PDFPackageTest.js
1<?php
2//---------------------------------------------------------------------------------------
3// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
4// Consult LICENSE.txt regarding license information.
5//---------------------------------------------------------------------------------------
6if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
7include("../../../PDFNetC/Lib/PDFNetPHP.php");
8include("../../LicenseKey/PHP/LicenseKey.php");
9
10// Relative path to the folder containing test files.
11$input_path = getcwd()."/../../TestFiles/";
12$output_path = $input_path."Output/";
13
14//-----------------------------------------------------------------------------------
15/// This sample illustrates how to create, extract, and manipulate PDF Portfolios
16/// (a.k.a. PDF Packages) using PDFNet SDK.
17//-----------------------------------------------------------------------------------
18
19function AddPackage($doc, $file, $desc) 
20{
21	$files = NameTree::Create($doc->GetSDFDoc(), "EmbeddedFiles");
22	$fs = FileSpec::Create($doc->GetSDFDoc(), $file, true);
23	$files->Put($file, strlen($file), $fs->GetSDFObj());
24	$fs->SetDesc($desc);
25
26	$collection = $doc->GetRoot()->FindObj("Collection");
27	if (!$collection) $collection = $doc->GetRoot()->PutDict("Collection");
28
29	// You could here manipulate any entry in the Collection dictionary. 
30	// For example, the following line sets the tile mode for initial view mode
31	// Please refer to section '2.3.5 Collections' in PDF Reference for details.
32	$collection->PutName("View", "T");
33}
34
35function AddCoverPage($doc) 
36{
37	// Here we dynamically generate cover page (please see ElementBuilder 
38	// sample for more extensive coverage of PDF creation API).
39	$page = $doc->PageCreate(new Rect(0.0, 0.0, 200.0, 200.0));
40
41	$builder = new ElementBuilder();
42	$writer = new ElementWriter();
43	$writer->Begin($page);
44	$font = Font::Create($doc->GetSDFDoc(), Font::e_helvetica);
45	$writer->WriteElement($builder->CreateTextBegin($font, 12.0));
46	$element = $builder->CreateTextRun("My PDF Collection");
47	$element->SetTextMatrix(1.0, 0.0, 0.0, 1.0, 50.0, 96.0);
48	$element->GetGState()->SetFillColorSpace(ColorSpace::CreateDeviceRGB());
49	$element->GetGState()->SetFillColor(new ColorPt(1.0, 0.0, 0.0));
50	$writer->WriteElement($element);
51	$writer->WriteElement($builder->CreateTextEnd());
52	$writer->End();
53	$doc->PagePushBack($page);
54
55	// Alternatively we could import a PDF page from a template PDF document
56	// (for an example please see PDFPage sample project).
57	// ...
58}
59
60//---------------------------------------------------------------------------------------
61
62	PDFNet::Initialize($LicenseKey);
63	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.
64
65	// Create a PDF Package.
66	
67	$doc = new PDFDoc();
68	AddPackage($doc, $input_path."numbered.pdf", "My File 1");
69	AddPackage($doc, $input_path."newsletter.pdf", "My Newsletter...");
70	AddPackage($doc, $input_path."peppers.jpg", "An image");
71	AddCoverPage($doc);
72	$doc->Save($output_path."package.pdf", SDFDoc::e_linearized);
73	$doc->Close();
74	echo nl2br("Done.\n");
75
76	// Extract parts from a PDF Package.
77	
78	$doc = new PDFDoc($output_path."package.pdf");
79	$doc->InitSecurityHandler();
80
81	$files = NameTree::Find($doc->GetSDFDoc(), "EmbeddedFiles");
82	if($files->IsValid()) 
83	{ 
84		// Traverse the list of embedded files.
85		$i = $files->GetIterator();
86		for ($counter = 0; $i->HasNext(); $i->Next(), ++$counter) 
87		{
88			$entry_name = $i->Key()->GetAsPDFText();
89			echo nl2br("Part: ".$entry_name."\n");
90			$file_spec = new FileSpec($i->Value());
91			$stm = new Filter($file_spec->GetFileData());
92			if ($stm) 
93			{
94				$stm->WriteToFile($output_path."extract_".$counter.".".pathinfo($entry_name, PATHINFO_EXTENSION), false);
95			}
96		}
97	}
98
99	$doc->Close();
100	PDFNet::Terminate();
101	echo nl2br("Done.\n");	
102?>
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6import site
7site.addsitedir("../../../PDFNetC/Lib")
8import sys, os
9from PDFNetPython import *
10
11sys.path.append("../../LicenseKey/PYTHON")
12from LicenseKey import *
13
14#-----------------------------------------------------------------------------------
15# This sample illustrates how to create, extract, and manipulate PDF Portfolios
16# (a.k.a. PDF Packages) using PDFNet SDK.
17#-----------------------------------------------------------------------------------
18
19def AddPackage(doc, file, desc):
20    files = NameTree.Create(doc.GetSDFDoc(), "EmbeddedFiles")
21    fs = FileSpec.Create(doc.GetSDFDoc(), file, True)
22    key = bytearray(file, "utf-8")
23    files.Put(key, len(key), fs.GetSDFObj())
24    fs.SetDesc(desc)
25    
26    collection = doc.GetRoot().FindObj("Collection")
27    if collection is None:
28        collection = doc.GetRoot().PutDict("Collection")
29    
30    # You could here manipulate any entry in the Collection dictionary. 
31    # For example, the following line sets the tile mode for initial view mode
32    # Please refer to section '2.3.5 Collections' in PDF Reference for details.
33    collection.PutName("View", "T");
34    
35def AddCoverPage(doc):
36    # Here we dynamically generate cover page (please see ElementBuilder 
37    # sample for more extensive coverage of PDF creation API).
38    page = doc.PageCreate(Rect(0, 0, 200, 200))
39    
40    b = ElementBuilder()
41    w = ElementWriter()
42    
43    w.Begin(page)
44    font = Font.Create(doc.GetSDFDoc(), Font.e_helvetica)
45    w.WriteElement(b.CreateTextBegin(font, 12))
46    e = b.CreateTextRun("My PDF Collection")
47    e.SetTextMatrix(1, 0, 0, 1, 50, 96)
48    e.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB())
49    e.GetGState().SetFillColor(ColorPt(1, 0, 0))
50    w.WriteElement(e)
51    w.WriteElement(b.CreateTextEnd())
52    w.End()
53    doc.PagePushBack(page)
54    
55    # Alternatively we could import a PDF page from a template PDF document
56    # (for an example please see PDFPage sample project).
57    # ...
58    
59
60def main():
61    PDFNet.Initialize(LicenseKey)
62    
63    # Relative path to the folder containing the test files.
64    input_path = "../../TestFiles/"
65    output_path = "../../TestFiles/Output/"
66    
67    # Create a PDF Package.
68    doc =PDFDoc()
69    AddPackage(doc, input_path + "numbered.pdf", "My File 1")
70    AddPackage(doc, input_path + "newsletter.pdf", "My Newsletter...")
71    AddPackage(doc, input_path + "peppers.jpg", "An image")
72    AddCoverPage(doc)
73    doc.Save(output_path + "package.pdf", SDFDoc.e_linearized)
74    doc.Close()
75    print("Done.")
76    
77    # Extract parts from a PDF Package
78    doc = PDFDoc(output_path + "package.pdf")
79    doc.InitSecurityHandler()
80    
81    files = NameTree.Find(doc.GetSDFDoc(), "EmbeddedFiles")
82    if files.IsValid():
83        # Traverse the list of embedded files.
84        i = files.GetIterator()
85        counter = 0
86        while i.HasNext():
87            entry_name = i.Key().GetAsPDFText()
88            print("Part: " + entry_name)
89            file_spec = FileSpec(i.Value())
90            stm = Filter(file_spec.GetFileData())
91            if stm != None:
92                stm.WriteToFile(output_path + "extract_" + str(counter) + os.path.splitext(entry_name)[1], False)
93            
94            i.Next()
95            counter = counter + 1
96    doc.Close()
97    PDFNet.Terminate()
98    print("Done.")
99
100if __name__ == '__main__':
101    main()
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6require '../../../PDFNetC/Lib/PDFNetRuby'
7include PDFNetRuby
8require '../../LicenseKey/RUBY/LicenseKey'
9
10$stdout.sync = true
11
12#-----------------------------------------------------------------------------------
13# This sample illustrates how to create, extract, and manipulate PDF Portfolios
14# (a.k.a. PDF Packages) using PDFNet SDK.
15#-----------------------------------------------------------------------------------
16
17def AddPackage(doc, file, desc)
18	files = NameTree.Create(doc.GetSDFDoc, "EmbeddedFiles")
19	fs = FileSpec.Create(doc.GetSDFDoc, file, true)
20	files.Put(file, file.length, fs.GetSDFObj)
21	fs.SetDesc(desc)
22	
23	collection = doc.GetRoot.FindObj("Collection")
24	if collection.nil?
25		collection = doc.GetRoot.PutDict("Collection")
26	end
27	
28	# You could here manipulate any entry in the Collection dictionary. 
29	# For example, the following line sets the tile mode for initial view mode
30	# Please refer to section '2.3.5 Collections' in PDF Reference for details.
31	collection.PutName("View", "T")
32end
33	
34def AddCoverPage(doc)
35	# Here we dynamically generate cover page (please see ElementBuilder 
36	# sample for more extensive coverage of PDF creation API).
37	page = doc.PageCreate(Rect.new(0, 0, 200, 200))
38	
39	b = ElementBuilder.new
40	w = ElementWriter.new
41	
42	w.Begin(page)
43	font = Font.Create(doc.GetSDFDoc, Font::E_helvetica)
44	w.WriteElement(b.CreateTextBegin(font, 12))
45	e = b.CreateTextRun("My PDF Collection")
46	e.SetTextMatrix(1, 0, 0, 1, 50, 96)
47	e.GetGState.SetFillColorSpace(ColorSpace.CreateDeviceRGB)
48	e.GetGState.SetFillColor(ColorPt.new(1, 0, 0))
49	w.WriteElement(e)
50	w.WriteElement(b.CreateTextEnd)
51	w.End
52	doc.PagePushBack(page)
53	
54	# Alternatively we could import a PDF page from a template PDF document
55	# (for an example please see PDFPage sample project).
56	# ...
57end
58	
59	PDFNet.Initialize(PDFTronLicense.Key)
60	
61	# Relative path to the folder containing the test files.
62	input_path = "../../TestFiles/"
63	output_path = "../../TestFiles/Output/"
64	
65	# Create a PDF Package.
66	doc = PDFDoc.new
67	AddPackage(doc, input_path + "numbered.pdf", "My File 1")
68	AddPackage(doc, input_path + "newsletter.pdf", "My Newsletter...")
69	AddPackage(doc, input_path + "peppers.jpg", "An image")
70	AddCoverPage(doc)
71	doc.Save(output_path + "package.pdf", SDFDoc::E_linearized)
72	doc.Close
73	puts "Done."
74	
75	# Extract parts from a PDF Package
76	doc = PDFDoc.new(output_path + "package.pdf")
77	doc.InitSecurityHandler
78	
79	files = NameTree.Find(doc.GetSDFDoc, "EmbeddedFiles")
80	if files.IsValid
81		# Traverse the list of embedded files.
82		i = files.GetIterator
83		counter = 0
84		while i.HasNext do
85			entry_name = i.Key.GetAsPDFText
86			puts "Part: " + entry_name
87			file_spec = FileSpec.new(i.Value)
88			stm = Filter.new(file_spec.GetFileData)
89			if !stm.nil?
90				stm.WriteToFile(output_path + "extract_" + counter.to_s + File.extname(entry_name), false)
91			end
92			i.Next
93			counter = counter + 1
94		end
95	end
96	doc.Close
97	PDFNet.Terminate
98	puts "Done."
1'
2' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3'
4
5Imports System
6
7Imports pdftron
8Imports pdftron.Common
9Imports pdftron.Filters
10Imports pdftron.SDF
11Imports pdftron.PDF
12
13Module PackageTestVB
14    Dim pdfNetLoader As PDFNetLoader
15    Sub New()
16        pdfNetLoader = pdftron.PDFNetLoader.Instance()
17    End Sub
18
19
20    Sub Main()
21
22        PDFNet.Initialize(PDFTronLicense.Key)
23
24        ' Relative path to the folder containing test files.
25        Dim input_path As String = "../../../../TestFiles/"
26        Dim output_path As String = "../../../../TestFiles/Output/"
27        Try
28
29            Using doc As PDFDoc = New PDFDoc
30                AddPackage(doc, input_path & "numbered.pdf", "My File 1")
31                AddPackage(doc, input_path & "newsletter.pdf", "My Newsletter...")
32                AddPackage(doc, input_path & "peppers.jpg", "An image")
33                AddCovePage(doc)
34                doc.Save(output_path & "package.pdf", SDFDoc.SaveOptions.e_linearized)
35                Console.WriteLine("Done.")
36            End Using
37
38        Catch e As PDFNetException
39            Console.WriteLine(e.Message)
40        End Try
41
42        Try
43
44            Using doc As PDFDoc = New PDFDoc(output_path & "package.pdf")
45                doc.InitSecurityHandler()
46                Dim files As pdftron.SDF.NameTree = NameTree.Find(doc, "EmbeddedFiles")
47
48                If files.IsValid() Then
49                    ' Traverse the list of embedded files.
50                    Dim i As NameTreeIterator = files.GetIterator()
51                    Dim counter As Integer = 0
52
53                    While i.HasNext()
54                        Dim entry_name As String = i.Key().GetAsPDFText()
55                        Console.WriteLine("Part: {0}", entry_name)
56                        Dim file_spec As FileSpec = New FileSpec(i.Value())
57                        Dim stm As Filter = file_spec.GetFileData()
58
59                        If stm IsNot Nothing Then
60                            Dim fname As String = output_path & "extract_" & counter.ToString() & System.IO.Path.GetExtension(entry_name)
61                            stm.WriteToFile(fname, False)
62                        End If
63
64                        i.Next()
65                        counter += 1
66                    End While
67                End If
68            End Using
69
70            Console.WriteLine("Done.")
71        Catch e As PDFNetException
72            Console.WriteLine(e.Message)
73        End Try
74        PDFNet.Terminate()
75    End Sub
76
77    Private Sub AddPackage(ByVal doc As PDFDoc, ByVal file As String, ByVal desc As String)
78        Dim files As NameTree = NameTree.Create(doc, "EmbeddedFiles")
79        Dim fs As FileSpec = FileSpec.Create(doc, file, True)
80        Dim file1_name As Byte() = System.Text.Encoding.UTF8.GetBytes(file)
81        files.Put(file1_name, fs.GetSDFObj())
82        fs.GetSDFObj().PutText("Desc", desc)
83        Dim collection As Obj = doc.GetRoot().FindObj("Collection")
84        If collection Is Nothing Then collection = doc.GetRoot().PutDict("Collection")
85    ' You could here manipulate any entry in the Collection dictionary. 
86    ' For example, the following line sets the tile mode for initial view mode
87    ' Please refer to section '2.3.5 Collections' in PDF Reference for details.
88        collection.PutName("View", "T")
89    End Sub
90
91    Private Sub AddCovePage(ByVal doc As PDFDoc)
92    ' Here we dynamically generate cover page (please see ElementBuilder 
93    ' sample for more extensive coverage of PDF creation API).
94        Dim page As Page = doc.PageCreate(New Rect(0, 0, 200, 200))
95
96        Using b As ElementBuilder = New ElementBuilder()
97
98            Using w As ElementWriter = New ElementWriter()
99                w.Begin(page)
100                Dim font As Font = Font.Create(doc, Font.StandardType1Font.e_helvetica)
101                w.WriteElement(b.CreateTextBegin(font, 12))
102                Dim e As Element = b.CreateTextRun("My PDF Collection")
103                e.SetTextMatrix(1, 0, 0, 1, 50, 96)
104                e.GetGState().SetFillColorSpace(ColorSpace.CreateDeviceRGB())
105                e.GetGState().SetFillColor(New ColorPt(1, 0, 0))
106                w.WriteElement(e)
107                w.WriteElement(b.CreateTextEnd())
108                w.End()
109                doc.PagePushBack(page)
110            End Using
111        End Using
112    ' Alternatively we could import a PDF page from a template PDF document
113    ' (for an example please see PDFPage sample project).
114    ' ...
115    End Sub
116End Module
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales