Sample code for editing an existing PDF document at the object level by using the Apryse SDK Cos/SDF low-level API. Sample code provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB.
Learn more about our Server SDK and PDF Editing & Manipulation Library.
1//
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3//
4
5using System;
6using pdftron;
7using pdftron.Common;
8using pdftron.Filters;
9using pdftron.SDF;
10using pdftron.PDF;
11
12namespace SDFTestCS
13{
14	/// <summary>
15	/// This sample illustrates how to use basic SDF API (also known as Cos) to edit an 
16	/// existing document.
17	/// </summary>
18	class Class1
19	{
20		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
21		static Class1() {}
22		
23		static void Main(string[] args)
24		{
25			PDFNet.Initialize(PDFTronLicense.Key);
26
27			// Relative path to the folder containing test files.
28			string input_path =  "../../../../TestFiles/";
29			string output_path = "../../../../TestFiles/Output/";
30
31
32			//------------------------------------------------------------------
33			Console.WriteLine("Opening the test file...");
34
35			try
36			{
37				// Here we create a SDF/Cos document directly from PDF file. In case you have 
38				// PDFDoc you can always access SDF/Cos document using PDFDoc.GetSDFDoc() method.
39				using (SDFDoc doc = new SDFDoc(input_path + "fish.pdf"))
40				{
41					doc.InitSecurityHandler();				
42					
43					Console.WriteLine("Modifying info dictionary, adding custom properties, embedding a stream...");
44
45					Obj trailer = doc.GetTrailer();	// Get the trailer
46
47					// Now we will change PDF document information properties using SDF API
48
49					// Get the Info dictionary. 
50					DictIterator itr = trailer.Find("Info");	
51					Obj info;
52					if (itr.HasNext()) 
53					{
54						info = itr.Value();
55						// Modify 'Producer' entry.
56						info.PutString("Producer", "PDFTron PDFNet");
57
58						// Read title entry (if it is present)
59						itr = info.Find("Author"); 
60						if (itr.HasNext()) 
61						{
62							info.PutString("Author", itr.Value().GetAsPDFText() + "- Modified");
63						}
64						else 
65						{
66							info.PutString("Author", "Joe Doe");
67						}
68					}
69					else 
70					{
71						// Info dict is missing. 
72						info = trailer.PutDict("Info");
73						info.PutString("Producer", "PDFTron PDFNet");
74						info.PutString("Title", "My document");
75					}
76
77					// Create a custom inline dictionary within Info dictionary
78					Obj custom_dict = info.PutDict("My Direct Dict");
79
80					// Add some key/value pairs
81					custom_dict.PutNumber("My Number", 100);
82
83					Obj my_array = custom_dict.PutArray("My Array");
84
85					// Create a custom indirect array within Info dictionary
86					Obj custom_array = doc.CreateIndirectArray();	
87					info.Put("My Indirect Array", custom_array);
88					
89					// Create indirect link to root
90					custom_array.PushBack(trailer.Get("Root").Value());
91
92					// Embed a custom stream (file my_stream.txt).
93					MappedFile embed_file = new MappedFile(input_path + "my_stream.txt");
94					FilterReader mystm = new FilterReader(embed_file);
95					custom_array.PushBack(doc.CreateIndirectStream(mystm));
96
97					// Save the changes.
98					Console.WriteLine("Saving modified test file...");
99					doc.Save(output_path + "sdftest_out.pdf", 0, "%PDF-1.4");
100				}
101
102				Console.WriteLine("Test completed.");
103			}
104			catch (PDFNetException e)
105			{
106				Console.WriteLine(e.Message);
107			}
108			PDFNet.Terminate();
109		}
110	}
111}
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 <PDF/PDFNet.h>
7#include <SDF/SDFDoc.h>
8#include <Filters/MappedFile.h>
9#include <Filters/FilterReader.h>
10#include <iostream>
11#include "../../LicenseKey/CPP/LicenseKey.h"
12
13using namespace std;
14
15using namespace pdftron;
16using namespace SDF;
17using namespace Filters;
18
19// This sample illustrates how to use basic SDF API (also known as Cos) to edit an 
20// existing document.
21
22int main(int argc, char *argv[])
23{
24	int ret = 0;
25	PDFNet::Initialize(LicenseKey);
26
27	// Relative path to the folder containing test files.
28	string input_path =  "../../TestFiles/";
29	string output_path = "../../TestFiles/Output/";
30
31	try
32	{
33		cout << "Opening the test file..." << endl;
34
35		// Here we create a SDF/Cos document directly from PDF file. In case you have 
36		// PDFDoc you can always access SDF/Cos document using PDFDoc.GetSDFDoc() method.
37		SDFDoc doc((input_path + "fish.pdf").c_str());
38		doc.InitSecurityHandler();
39
40		cout << "Modifying info dictionary, adding custom properties, embedding a stream..." << endl;
41		Obj trailer = doc.GetTrailer();			// Get the trailer
42
43		// Now we will change PDF document information properties using SDF API
44
45		// Get the Info dictionary. 
46		DictIterator itr = trailer.Find("Info");	
47		Obj info;
48		if (itr.HasNext()) 
49		{
50			info = itr.Value();
51			// Modify 'Producer' entry.
52			info.PutString("Producer", "PDFTron PDFNet");
53
54			// Read title entry (if it is present)
55			itr = info.Find("Author"); 
56			if (itr.HasNext()) 
57			{
58				UString oldstr;
59				itr.Value().GetAsPDFText(oldstr);
60				info.PutText("Author",oldstr+"- Modified");
61			}
62			else 
63			{
64				info.PutString("Author", "Me, myself, and I");
65			}
66		}
67		else 
68		{
69			// Info dict is missing. 
70			info = trailer.PutDict("Info");
71			info.PutString("Producer", "PDFTron PDFNet");
72			info.PutString("Title", "My document");
73		}
74
75		// Create a custom inline dictionary within Info dictionary
76		Obj custom_dict = info.PutDict("My Direct Dict");
77		custom_dict.PutNumber("My Number", 100);	 // Add some key/value pairs
78		custom_dict.PutArray("My Array");
79
80		// Create a custom indirect array within Info dictionary
81		Obj custom_array = doc.CreateIndirectArray();	
82		info.Put("My Indirect Array", custom_array);	// Add some entries
83		
84		// Create indirect link to root
85		custom_array.PushBack(trailer.Get("Root").Value());
86
87		// Embed a custom stream (file mystream.txt).
88		MappedFile embed_file((input_path + "my_stream.txt"));
89		FilterReader mystm(embed_file);
90		custom_array.PushBack( doc.CreateIndirectStream(mystm) );
91
92		// Save the changes.
93		cout << "Saving modified test file..." << endl;
94		doc.Save((output_path + "sdftest_out.pdf").c_str(), 0, 0, "%PDF-1.4");
95
96		cout << "Test completed." << endl;
97	}
98	catch(Common::Exception& e)
99	{
100		cout << e << endl;
101		ret = 1;
102	}
103	catch(...)
104	{
105		cout << "Unknown Exception" << endl;
106		ret = 1;
107	}
108
109	PDFNet::Terminate();
110	return ret;    
111}
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	. "pdftron"
10)
11
12import  "pdftron/Samples/LicenseKey/GO"
13
14// This sample illustrates how to use basic SDF API (also known as Cos) to edit an 
15// existing document.
16
17func main(){
18    PDFNetInitialize(PDFTronLicense.Key)
19    
20    // Relative path to the folder containing the test files.
21    inputPath := "../../TestFiles/"
22    outputPath := "../../TestFiles/Output/"
23    
24    fmt.Println("Opening the test file...")
25    
26    // Here we create a SDF/Cos document directly from PDF file. In case you have 
27    // PDFDoc you can always access SDF/Cos document using PDFDoc.GetSDFDoc() method.
28    doc := NewSDFDoc(inputPath + "fish.pdf")
29    doc.InitSecurityHandler()
30    
31    fmt.Println("Modifying info dictionary, adding custom properties, embedding a stream...")
32    trailer := doc.GetTrailer()  // Get the trailer
33    
34    // Now we will change PDF document information properties using SDF API
35    
36    // Get the Info dictionary
37    itr := trailer.Find("Info")
38    info := NewObj()
39    if itr.HasNext(){
40        info = itr.Value()
41        // Modify 'Producer' entry
42        info.PutString("Producer", "PDFTron PDFNet")
43        
44        // Read title entry (if it is present)
45        itr = info.Find("Author")
46        if itr.HasNext(){
47		fmt.Println("Author inside")
48            oldstr := itr.Value().GetAsPDFText()
49            info.PutText("Author", oldstr + "- Modified")
50        }else{
51            info.PutString("Author", "Me, myself, and I")
52		}
53    }else{
54        // Info dict is missing.
55        info = trailer.PutDict("Info")
56        info.PutString("Producer", "PDFTron PDFNet")
57        info.PutString("Title", "My document")
58    }    
59    // Create a custom inline dictionary within Info dictionary
60    customDict := info.PutDict("My Direct Dict")
61    customDict.PutNumber("My Number", 100)     // Add some key/value pairs
62    customDict.PutArray("My Array")
63    
64    // Create a custom indirect array within Info dictionary
65    customArray := doc.CreateIndirectArray()
66    info.Put("My Indirect Array", customArray)    // Add some entries
67    
68    // Create indirect link to root
69    customArray.PushBack(trailer.Get("Root").Value())
70    
71    // Embed a custom stream (file mystream.txt).
72    embedFile := NewMappedFile(inputPath + "my_stream.txt")
73    mystm := NewFilterReader(embedFile)
74    customArray.PushBack( doc.CreateIndirectStream(mystm) )
75    
76    // Save the changes.
77    fmt.Println("Saving modified test file...")
78    doc.Save(outputPath + "sdftest_out.pdf", uint(0), "%PDF-1.4")
79    doc.Close()
80    
81    PDFNetTerminate()
82    fmt.Println("Test Completed")
83    
84}
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.pdf.*;
7import com.pdftron.sdf.*;
8import com.pdftron.filters.*;
9
10// This sample illustrates how to use basic SDF API (also known as Cos) to edit an 
11// existing document.
12public class SDFTest {
13    public static void main(String[] args) {
14        PDFNet.initialize(PDFTronLicense.Key());
15
16        // Relative path to the folder containing test files.
17        String input_path = "../../TestFiles/";
18        String output_path = "../../TestFiles/Output/";
19
20        try {
21            System.out.println("Opening the test file...");
22
23            // Here we create a SDF/Cos document directly from PDF file. In case you have
24            // PDFDoc you can always access SDF/Cos document using PDFDoc.GetSDFDoc() method.
25            SDFDoc doc = new SDFDoc((input_path + "fish.pdf"));
26            doc.initSecurityHandler();
27
28            System.out.println("Modifying info dictionary, adding custom properties, embedding a stream...");
29            Obj trailer = doc.getTrailer();            // Get the trailer
30
31            // Now we will change PDF document information properties using SDF API
32
33            // Get the Info dictionary.
34            DictIterator itr = trailer.find("Info");
35            Obj info;
36            if (itr.hasNext()) {
37                info = itr.value();
38                // Modify 'Producer' entry.
39                info.putString("Producer", "PDFTron PDFNet");
40
41                // Read title entry (if it is present)
42                itr = info.find("Author");
43                if (itr.hasNext()) {
44                    String oldstr = itr.value().getAsPDFText();
45
46                    info.putText("Author", oldstr + "- Modified");
47                } else {
48                    info.putString("Author", "Me, myself, and I");
49                }
50            } else {
51                // Info dict is missing.
52                info = trailer.putDict("Info");
53                info.putString("Producer", "PDFTron PDFNet");
54                info.putString("Title", "My document");
55            }
56
57            // Create a custom inline dictionary within Info dictionary
58            Obj custom_dict = info.putDict("My Direct Dict");
59            custom_dict.putNumber("My Number", 100);     // Add some key/value pairs
60            custom_dict.putArray("My Array");
61
62            // Create a custom indirect array within Info dictionary
63            Obj custom_array = doc.createIndirectArray();
64            info.put("My Indirect Array", custom_array);    // Add some entries
65
66            // Create indirect link to root
67            custom_array.pushBack(trailer.get("Root").value());
68
69            // Embed a custom stream (file mystream.txt).
70            MappedFile embed_file = new MappedFile(input_path + "my_stream.txt");
71            FilterReader mystm = new FilterReader(embed_file);
72            custom_array.pushBack(doc.createIndirectStream(mystm));
73
74            // Save the changes.
75            System.out.println("Saving modified test file...");
76            doc.save(output_path + "sdftest_out.pdf", SDFDoc.SaveMode.NO_FLAGS, null, "%PDF-1.4");
77            // output PDF doc
78            doc.close();
79
80            System.out.println("Test completed.");
81        } catch (Exception e) {
82            System.out.println(e);
83        }
84
85        PDFNet.terminate();
86    }
87}
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// This sample illustrates how to use basic SDF API (also known as Cos) to edit an 
7// existing document.
8
9const { PDFNet } = require('@pdftron/pdfnet-node');
10const PDFTronLicense = require('../LicenseKey/LicenseKey');
11
12((exports) => {
13
14  exports.runSDFTest = () => {
15
16    const main = async() => {
17      // Relative path to the folder containing test files.
18      const inputPath = '../TestFiles/';
19
20      try {
21        console.log('Opening the test file...');
22        // Here we create a SDF/Cos document directly from PDF file. In case you have
23        // PDFDoc you can always access SDF/Cos document using PDFDoc.GetSDFDoc() method.
24        const doc = await PDFNet.SDFDoc.createFromFileUString(inputPath + 'fish.pdf');
25        doc.initSecurityHandler();
26        console.log('Modifying into dictionary, adding custom properties, embedding a stream...');
27
28        const trailer = await doc.getTrailer(); // Get the trailer
29
30        // Now we will change PDF document information properties using SDF API
31
32        // Get the Info dictionary.
33
34        let itr = await trailer.find('Info');
35        let info;
36        if (await itr.hasNext()) {
37          info = await itr.value();
38          // Modify 'Producer' entry.
39          info.putString('Producer', 'PDFTron PDFNet');
40
41          // read title entry if it is present
42          itr = await info.find('Author');
43          if (await itr.hasNext()) {
44            const itrval = await itr.value();
45            const oldstr = await itrval.getAsPDFText();
46            info.putText('Author', oldstr + ' - Modified');
47          } else {
48            info.putString('Author', 'Me, myself, and I');
49          }
50        } else {
51          // Info dict is missing.
52          info = await trailer.putDict('Info');
53          info.putString('Producer', 'PDFTron PDFNet');
54          info.putString('Title', 'My document');
55        }
56
57        // Create a custom inline dictionary within Infor dictionary
58        const customDict = await info.putDict('My Direct Dict');
59        customDict.putNumber('My Number', 100); // Add some key/value pairs
60        customDict.putArray('My Array');
61
62        // Create a custom indirect array within Info dictionary
63        const customArray = await doc.createIndirectArray();
64        info.put('My Indirect Array', customArray); // Add some entries
65
66        // create indirect link to root
67        const trailerRoot = await trailer.get('Root');
68        customArray.pushBack((await trailerRoot.value()));
69
70        // Embed a custom stream (file mystream.txt).
71        const embedFile = await PDFNet.Filter.createMappedFileFromUString(inputPath + 'my_stream.txt');
72        const mystm = await PDFNet.FilterReader.create(embedFile);
73        const indStream = await doc.createIndirectStreamFromFilter(mystm);
74        customArray.pushBack(indStream);
75
76        console.log('Saving modified test file...');
77        await doc.save(inputPath + 'Output/sdftest_out.pdf', 0, '%PDF-1.4');
78        console.log('Test completed.');
79      } catch (err) {
80        console.log(err);
81      }
82    };
83    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error){console.log('Error: ' + JSON.stringify(error));}).then(function(){return PDFNet.shutdown();});
84  };
85  exports.runSDFTest();
86})(exports);
87// eslint-disable-next-line spaced-comment
88//# sourceURL=SDFTest.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 the test files.
11$input_path = getcwd()."/../../TestFiles/";
12$output_path = $input_path."Output/";
13
14// This sample illustrates how to use basic SDF API (also known as Cos) to edit an 
15// existing document.
16
17	PDFNet::Initialize($LicenseKey);
18	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.
19
20	echo nl2br("Opening the test file...\n");
21
22	// Here we create a SDF/Cos document directly from PDF file. In case you have 
23	// PDFDoc you can always access SDF/Cos document using PDFDoc.GetSDFDoc() method.
24	$doc = new SDFDoc($input_path."fish.pdf");
25	$doc->InitSecurityHandler();
26
27	echo nl2br("Modifying info dictionary, adding custom properties, embedding a stream...\n");
28	$trailer = $doc->GetTrailer();			// Get the trailer
29
30	// Now we will change PDF document information properties using SDF API
31
32	// Get the Info dictionary. 
33	$itr = $trailer->Find("Info");
34	if ($itr->HasNext()) 
35	{
36		$info = $itr->Value();
37		// Modify 'Producer' entry.
38		$info->PutString("Producer", "PDFTron PDFNet");
39
40		// Read title entry (if it is present)
41		$itr = $info->Find("Author"); 
42		if ($itr->HasNext()) 
43		{
44			// Modify 'Producer' entry
45			$itr->Value()->PutString("Producer", "PDFTron PDFNet");
46
47			// Read title entry (if it is present)
48			$itr = $info->Find("Author");
49			if ($itr->HasNext()) {
50				$oldstr = $itr->Value()->GetAsPDFTest();
51				$info->PutText("Author",$oldstr."- Modified");
52			}
53			else {
54				$info->PutString("Author", "Me, myself, and I");
55			}
56		}
57		else 
58		{
59			$info->PutString("Author", "Me, myself, and I");
60		}
61	}
62	else 
63	{
64		// Info dict is missing. 
65		$info = $trailer->PutDict("Info");
66		$info->PutString("Producer", "PDFTron PDFNet");
67		$info->PutString("Title", "My document");
68	}
69
70	// Create a custom inline dictionary within Info dictionary
71	$custom_dict = $info->PutDict("My Direct Dict");
72	$custom_dict->PutNumber("My Number", 100);	 // Add some key/value pairs
73	$custom_dict->PutArray("My Array");
74
75	// Create a custom indirect array within Info dictionary
76	$custom_array = $doc->CreateIndirectArray();	
77	$info->Put("My Indirect Array", $custom_array);	// Add some entries
78		
79	// Create indirect link to root
80	$custom_array->PushBack($trailer->Get("Root")->Value());
81
82	// Embed a custom stream (file mystream.txt).
83	$embed_file = new MappedFile($input_path."my_stream.txt");
84	$mystm = new FilterReader($embed_file);
85	$custom_array->PushBack( $doc->CreateIndirectStream($mystm) );
86
87	// Save the changes.
88	echo nl2br("Saving modified test file...\n");
89	$doc->Save($output_path."sdftest_out.pdf", 0, "%PDF-1.4");
90	$doc->Close();
91	PDFNet::Terminate();
92	echo nl2br("Test completed.\n");
93	
94	
95?>
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# This sample illustrates how to use basic SDF API (also known as Cos) to edit an 
13# existing document.
14
15	PDFNet.Initialize(PDFTronLicense.Key)
16	
17	# Relative path to the folder containing the test files.
18	input_path = "../../TestFiles/"
19	output_path = "../../TestFiles/Output/"
20	
21	puts "Opening the test file..."
22	
23	# Here we create a SDF/Cos document directly from PDF file. In case you have 
24	# PDFDoc you can always access SDF/Cos document using PDFDoc.GetSDFDoc method.
25	doc = SDFDoc.new(input_path + "fish.pdf")
26	doc.InitSecurityHandler
27	
28	puts "Modifying info dictionary, adding custom properties, embedding a stream..."
29	trailer = doc.GetTrailer  # Get the trailer
30	
31	# Now we will change PDF document information properties using SDF API
32	
33	# Get the Info dictionary
34	itr = trailer.Find("Info")
35	info = Obj.new
36	if itr.HasNext
37		info = itr.Value
38		# Modify 'Producer' entry
39		info.PutString("Producer", "PDFTron PDFNet")
40		
41		# Read title entry (if it is present)
42		itr = info.Find("Author")
43		if itr.HasNext
44			oldstr = itr.Value.GetAsPDFTest
45			info.PutText("Author", oldstr + "- Modified")
46		else
47			info.PutString("Author", "Me, myself, and I")
48		end
49	else
50		# Info dict is missing.
51		info = trailer.PutDict("Info")
52		info.PutString("Producer", "PDFTron PDFNet")
53		info.PutString("Title", "My document")
54	end
55		
56	# Create a custom inline dictionary within Info dictionary
57	custom_dict = info.PutDict("My Direct Dict")
58	custom_dict.PutNumber("My Number", 100)	 # Add some key/value pairs
59	custom_dict.PutArray("My Array")
60	
61	# Create a custom indirect array within Info dictionary
62	custom_array = doc.CreateIndirectArray
63	info.Put("My Indirect Array", custom_array)	# Add some entries
64	
65	# Create indirect link to root
66	custom_array.PushBack(trailer.Get("Root").Value)
67	
68	# Embed a custom stream (file mystream.txt).
69	embed_file = MappedFile.new(input_path + "my_stream.txt")
70	mystm = FilterReader.new(embed_file)
71	custom_array.PushBack( doc.CreateIndirectStream(mystm) )
72	
73	# Save the changes.
74	puts "Saving modified test file..."
75	doc.Save(output_path + "sdftest_out.pdf", 0, "%PDF-1.4")
76	doc.Close
77	PDFNet.Terminate
78	puts "Test Completed"
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
9from PDFNetPython import *
10
11sys.path.append("../../LicenseKey/PYTHON")
12from LicenseKey import *
13
14
15# This sample illustrates how to use basic SDF API (also known as Cos) to edit an 
16# existing document.
17
18def main():
19    PDFNet.Initialize(LicenseKey)
20    
21    # Relative path to the folder containing the test files.
22    input_path = "../../TestFiles/"
23    output_path = "../../TestFiles/Output/"
24    
25    print("Opening the test file...")
26    
27    # Here we create a SDF/Cos document directly from PDF file. In case you have 
28    # PDFDoc you can always access SDF/Cos document using PDFDoc.GetSDFDoc() method.
29    doc = SDFDoc(input_path + "fish.pdf")
30    doc.InitSecurityHandler()
31    
32    print("Modifying info dictionary, adding custom properties, embedding a stream...")
33    trailer = doc.GetTrailer()  # Get the trailer
34    
35    # Now we will change PDF document information properties using SDF API
36    
37    # Get the Info dictionary
38    itr = trailer.Find("Info")
39    info = Obj()
40    if itr.HasNext():
41        info = itr.Value()
42        # Modify 'Producer' entry
43        info.PutString("Producer", "PDFTron PDFNet")
44        
45        # Read title entry (if it is present)
46        itr = info.Find("Author")
47        if itr.HasNext():
48            oldstr = itr.Value().GetAsPDFTest()
49            info.PutText("Author", oldstr + "- Modified")
50        else:
51            info.PutString("Author", "Me, myself, and I")
52    else:
53        # Info dict is missing.
54        info = trailer.PutDict("Info")
55        info.PutString("Producer", "PDFTron PDFNet")
56        info.PutString("Title", "My document")
57        
58    # Create a custom inline dictionary within Info dictionary
59    custom_dict = info.PutDict("My Direct Dict")
60    custom_dict.PutNumber("My Number", 100)     # Add some key/value pairs
61    custom_dict.PutArray("My Array")
62    
63    # Create a custom indirect array within Info dictionary
64    custom_array = doc.CreateIndirectArray()
65    info.Put("My Indirect Array", custom_array)    # Add some entries
66    
67    # Create indirect link to root
68    custom_array.PushBack(trailer.Get("Root").Value())
69    
70    # Embed a custom stream (file mystream.txt).
71    embed_file = MappedFile(input_path + "my_stream.txt")
72    mystm = FilterReader(embed_file)
73    custom_array.PushBack( doc.CreateIndirectStream(mystm) )
74    
75    # Save the changes.
76    print("Saving modified test file...")
77    doc.Save(output_path + "sdftest_out.pdf", 0, "%PDF-1.4")
78    doc.Close()
79    
80    PDFNet.Terminate()
81    print("Test Completed")
82    
83if __name__ == '__main__':
84    main()
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 SDFTestVB
14	Dim pdfNetLoader As PDFNetLoader
15	Sub New()
16		pdfNetLoader = pdftron.PDFNetLoader.Instance()
17	End Sub
18
19	' This sample illustrates how to use basic SDF API (also known as Cos) to edit an 
20	' existing document.
21	Sub Main()
22
23		PDFNet.Initialize(PDFTronLicense.Key)
24
25		' Relative path to the folder containing test files.
26		Dim input_path As String = "../../../../TestFiles/"
27		Dim output_path As String = "../../../../TestFiles/Output/"
28
29		Try
30			'------------------------------------------------------------------
31			Console.WriteLine("-------------------------------------------------")
32			Console.WriteLine("Opening the test file...")
33
34			' Here we create a SDF/Cos document directly from PDF file. In case you have 
35			' PDFDoc you can always access SDF/Cos document using PDFDoc.GetSDFDoc() method.
36			Using doc As SDFDoc = New SDFDoc(input_path + "fish.pdf")
37				doc.InitSecurityHandler()
38
39				Console.WriteLine("-------------------------------------------------")
40				Console.WriteLine("Modifying info dictionary, adding custom properties, embedding a stream...")
41
42				Dim trailer As Obj = doc.GetTrailer()		   ' Get the trailer
43
44				' Now we will change PDF document information properties using SDF API
45
46				' Get the Info dictionary. 
47				Dim itr As DictIterator = trailer.Find("Info")
48				Dim info As Obj
49				If itr.HasNext() Then
50					info = itr.Value()
51					' Modify 'Producer' entry.
52					info.PutString("Producer", "PDFTron PDFNet")
53
54					' Read title entry (if it is present)
55					itr = info.Find("Author")
56					If Not itr.HasNext() Then
57						info.PutString("Author", "Joe Doe")
58					Else
59						info.PutString("Author", itr.Value().GetAsPDFText() + "- Modified")
60					End If
61				Else
62					' Info dict is missing. 
63					info = trailer.PutDict("Info")
64					info.PutString("Producer", "PDFTron PDFNet")
65					info.PutString("Title", "My document")
66				End If
67
68
69				' Create a custom inline dictionary within Info dictionary
70				Dim custom_dict As Obj = info.PutDict("My Direct Dict")
71
72				' Add some key/value pairs
73				custom_dict.PutNumber("My Number", 100)
74				Dim my_array As Obj = custom_dict.PutArray("My Array")
75
76				' Create a custom indirect array within Info dictionary
77				Dim custom_array As Obj = doc.CreateIndirectArray()
78				info.Put("My Indirect Array", custom_array)
79
80				' Create indirect link to root
81				custom_array.PushBack(trailer.Get("Root").Value())
82
83				' Embed a custom stream (file my_stream.txt).
84				Dim embed_file As MappedFile = New MappedFile(input_path + "my_stream.txt")
85				Dim mystm As FilterReader = New FilterReader(embed_file)
86				custom_array.PushBack(doc.CreateIndirectStream(mystm))
87
88				' Save the changes.
89				Console.WriteLine("Saving modified test file...")
90				doc.Save(output_path + "sdftest_out.pdf", 0, "%PDF-1.4")
91
92				Console.WriteLine("Done. Result saved in sdftest_out.pdf")
93			End Using
94		Catch ex As PDFNetException
95			Console.WriteLine(ex.Message)
96		Catch ex As Exception
97			MsgBox(ex.Message)
98		End Try
99		PDFNet.Terminate()
100	End Sub
101End Module
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales