Sample code for using Apryse SDK to programmatically edit an existing PDF document's page display list and the graphics state attributes on existing elements. In particular, this sample strips all images from the page and changes the text color to blue, provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. You can also build a GUI with interactive PDF editor widgets. Some of Apryse SDK's other functions for programmatically editing PDFs include the Cos/SDF low-level API, page manipulation, and more. 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 System.Collections.Generic;
7
8using pdftron;
9using pdftron.Common;
10using pdftron.Filters;
11using pdftron.SDF;
12using pdftron.PDF;
13
14using XSet = System.Collections.Generic.List<int>;
15
16namespace ElementEditTestCS
17{
18	/// <summary>
19	/// The sample code shows how to edit the page display list and how to modify graphics state 
20	/// attributes on existing Elements. In particular the sample program strips all images from 
21	/// the page, changes path fill color to red, and changes text fill color to blue. 
22	/// </summary>
23	class Class1
24	{
25		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
26		static Class1() {}
27		
28		static void ProcessElements(ElementReader reader, ElementWriter writer, XSet visited)
29		{
30			Element element;
31			while ((element = reader.Next()) != null) // Read page contents
32			{
33				switch (element.GetType())
34				{
35					case Element.Type.e_image:
36					case Element.Type.e_inline_image:
37							// remove all images by skipping them
38							break;
39					case Element.Type.e_path:
40						{
41							// Set all paths to red color.
42							GState gs = element.GetGState();
43							gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB());
44							gs.SetFillColor(new ColorPt(1, 0, 0));
45							writer.WriteElement(element);
46							break;
47						}
48					case Element.Type.e_text:
49						{
50							// Set all text to blue color.
51							GState gs = element.GetGState();
52							gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB());
53							gs.SetFillColor(new ColorPt(0, 0, 1));
54							writer.WriteElement(element);
55							break;
56						}
57					case Element.Type.e_form:
58						{
59							writer.WriteElement(element); // write Form XObject reference to current stream
60
61							Obj form_obj = element.GetXObject();
62							if (!visited.Contains(form_obj.GetObjNum())) // if this XObject has not been processed
63							{
64								// recursively process the Form XObject
65								visited.Add(form_obj.GetObjNum());
66								ElementWriter new_writer = new ElementWriter();
67
68								reader.FormBegin();
69								new_writer.Begin(form_obj, true);
70
71								reader.ClearChangeList();
72								new_writer.SetDefaultGState(reader);
73
74								ProcessElements(reader, new_writer, visited);
75								new_writer.End();
76								reader.End();
77							}
78							break;
79						}
80					default:
81						writer.WriteElement(element);
82						break;
83				}
84			}
85		}
86
87		/// <summary>
88		/// The main entry point for the application.
89		/// </summary>
90		[STAThread]
91		static void Main(string[] args)
92		{
93			PDFNet.Initialize(PDFTronLicense.Key);
94
95			// Relative path to the folder containing test files.
96			string input_path = "../../../../TestFiles/";
97			string output_path = "../../../../TestFiles/Output/";
98			string input_filename = "newsletter.pdf";
99			string output_filename = "newsletter_edited.pdf";
100
101			try
102			{
103				Console.WriteLine("Opening the input file...");
104				using (PDFDoc doc = new PDFDoc(input_path + input_filename))
105				{
106					doc.InitSecurityHandler();
107
108					ElementWriter writer = new ElementWriter();
109					ElementReader reader = new ElementReader();
110					XSet visited = new XSet();
111
112					PageIterator itr = doc.GetPageIterator();
113
114					while (itr.HasNext())
115					{
116						try
117						{
118							Page page = itr.Current();
119							visited.Add(page.GetSDFObj().GetObjNum());
120
121							reader.Begin(page);
122							writer.Begin(page, ElementWriter.WriteMode.e_replacement, false, true, page.GetResourceDict());
123
124							ProcessElements(reader, writer, visited);
125							writer.End();
126							reader.End();
127
128							itr.Next();
129						}
130						catch (PDFNetException e)
131						{
132							Console.WriteLine(e.Message);
133						}
134					}
135
136					doc.Save(output_path + output_filename, SDFDoc.SaveOptions.e_remove_unused);
137					Console.WriteLine("Done. Result saved in {0}...", output_filename);
138				}
139			}
140			catch (PDFNetException e)
141			{
142				Console.WriteLine(e.Message);
143			}
144			PDFNet.Terminate();
145		}
146	}
147}
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 <PDF/PDFDoc.h>
8#include <PDF/ElementWriter.h>
9#include <PDF/ElementReader.h>
10#include <SDF/Obj.h>
11#include <set>
12#include <iostream>
13#include "../../LicenseKey/CPP/LicenseKey.h"
14
15using namespace pdftron;
16using namespace std;
17using namespace SDF;
18using namespace PDF;
19
20
21//---------------------------------------------------------------------------------------
22// The sample code shows how to edit the page display list and how to modify graphics state 
23// attributes on existing Elements. In particular the sample program strips all images from 
24// the page, changes path fill color to red, and changes text fill color to blue. 
25//---------------------------------------------------------------------------------------
26
27// XObjects are guaranteed to have unique object numbers 
28typedef set<pdftron::UInt32> XObjSet;
29
30
31static void ProcessElements(ElementReader& reader, ElementWriter& writer, XObjSet& visited) 
32{
33	Element element;
34	while (element = reader.Next()) // Read page contents
35	{
36		switch (element.GetType())
37		{
38		case Element::e_image: 
39		case Element::e_inline_image: 
40			// remove all images by skipping them			
41			break;
42		case Element::e_path:
43			{
44				// Set all paths to red color.
45				GState gs = element.GetGState();
46				gs.SetFillColorSpace(ColorSpace::CreateDeviceRGB());
47				ColorPt cp(1, 0, 0);
48				gs.SetFillColor(cp);
49				writer.WriteElement(element);
50				break;
51			}
52		case Element::e_text:
53			{
54				// Set all text to blue color.
55				GState gs = element.GetGState();
56				gs.SetFillColorSpace(ColorSpace::CreateDeviceRGB());
57				ColorPt cp(0, 0, 1);
58				gs.SetFillColor(cp);
59				writer.WriteElement(element);
60				break;
61			}
62		case Element::e_form:
63			{
64				writer.WriteElement(element); // write Form XObject reference to current stream
65
66				Obj form_obj = element.GetXObject();
67				if (visited.find(form_obj.GetObjNum()) == visited.end()) // if this XObject has not been processed
68				{
69					// recursively process the Form XObject
70					visited.insert(form_obj.GetObjNum());
71					ElementWriter new_writer;
72					reader.FormBegin();
73					new_writer.Begin(form_obj);
74
75					reader.ClearChangeList();
76					new_writer.SetDefaultGState(reader); 
77
78					ProcessElements(reader, new_writer, visited);
79					new_writer.End();
80					reader.End();
81				}
82				break; 
83			}
84		default:
85			writer.WriteElement(element);
86		}
87	}
88}
89
90int main(int argc, char *argv[])
91{
92	int ret = 0;
93	PDFNet::Initialize(LicenseKey);
94
95	// Relative path to the folder containing test files.
96	string input_path =  "../../TestFiles/";
97	string output_path = "../../TestFiles/Output/";
98	string input_filename = "newsletter.pdf";
99	string output_filename = "newsletter_edited.pdf";
100
101	try 
102	{
103		cout << "Opening the input file..." << endl;
104		PDFDoc doc(input_path + input_filename);
105		doc.InitSecurityHandler();
106
107		ElementWriter writer;
108		ElementReader reader;
109		XObjSet visited;
110		
111		// Process each page in the document
112		for (PageIterator itr = doc.GetPageIterator();itr.HasNext();itr.Next())
113		{
114			try {
115				Page page = itr.Current();
116				visited.insert(page.GetSDFObj().GetObjNum());
117
118				reader.Begin(page);
119				writer.Begin(page, ElementWriter::e_replacement, false, true, page.GetResourceDict());
120				ProcessElements(reader, writer, visited);
121				writer.End();
122				reader.End();
123			}
124			catch (Common::Exception& e)
125			{
126				cout << e << endl;
127			}
128		}
129
130		// Save modified document
131		doc.Save(output_path + output_filename, SDFDoc::e_remove_unused, 0);		
132		cout << "Done. Result saved in " << output_filename <<"..." << endl;
133	}
134	catch(Common::Exception& e)
135	{
136		cout << e << endl;
137		ret = 1;
138	}
139	catch(...)
140	{
141		cout << "Unknown Exception" << endl;
142		ret = 1;
143	}
144	PDFNet::Terminate();
145	return ret;
146}
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//---------------------------------------------------------------------------------------
15// The sample code shows how to edit the page display list and how to modify graphics state 
16// attributes on existing Elements. In particular the sample program strips all images from 
17// the page, changes path fill color to red, and changes text color to blue. 
18//---------------------------------------------------------------------------------------
19
20func ProcessElements(reader ElementReader, writer ElementWriter, omap map[uint]Obj){
21    element := reader.Next()     // Read page contents
22    for element.GetMp_elem().Swigcptr() != 0{
23        etype := element.GetType()
24        if etype == ElementE_image{
25            // remove all images by skipping them
26        }else if etype == ElementE_inline_image{            
27            // remove all images by skipping them
28        }else if etype == ElementE_path{
29            // Set all paths to red color.
30            gs := element.GetGState()
31            gs.SetFillColorSpace(ColorSpaceCreateDeviceRGB())
32            gs.SetFillColor(NewColorPt(1.0, 0.0, 0.0))
33            writer.WriteElement(element)
34        }else if etype == ElementE_text{    // Process text strings...
35            // Set all text to blue color.
36            gs := element.GetGState()
37            gs.SetFillColorSpace(ColorSpaceCreateDeviceRGB())
38            cp := NewColorPt(0.0, 0.0, 1.0)
39            gs.SetFillColor(cp)
40            writer.WriteElement(element)
41        }else if etype == ElementE_form{    // Recursively process form XObjects
42            o := element.GetXObject()
43            omap[o.GetObjNum()] = o
44            writer.WriteElement(element)
45        }else{
46            writer.WriteElement(element)
47		}
48        element = reader.Next()
49	}
50}
51
52func main(){
53    PDFNetInitialize(PDFTronLicense.Key)
54    
55    // Relative path to the folder containing the test files.
56    inputPath := "../../TestFiles/"
57    outputPath := "../../TestFiles/Output/"
58    inputFilename := "newsletter.pdf"
59    outputFilename := "newsletter_edited.pdf"
60    
61    
62    // Open the test file
63    fmt.Println("Opening the input file...")
64    doc := NewPDFDoc(inputPath + inputFilename)
65    doc.InitSecurityHandler()
66    
67    writer := NewElementWriter()
68    reader := NewElementReader()
69    
70    itr := doc.GetPageIterator()
71    
72    for itr.HasNext(){
73        page := itr.Current()
74        reader.Begin(page)
75        writer.Begin(page, ElementWriterE_replacement, false)
76        var map1 = make(map[uint]Obj)
77        ProcessElements(reader, writer, map1)
78        writer.End()
79        reader.End()
80		
81        var map2 = make(map[uint]Obj)
82        for !(len(map1) == 0 && len(map2) == 0){
83            for k, v := range map1{
84                obj := v
85                writer.Begin(obj)
86                reader.Begin(obj, page.GetResourceDict())
87                ProcessElements(reader, writer, map2)
88                reader.End()
89                writer.End()
90                delete(map1, k)
91			}
92            if (len(map1) == 0 && len(map2) != 0){
93                //map1.update(map2)
94				for key, value := range map2{         
95					map1[key] = value 
96				}
97				//map2.clear()
98				for k := range map2 {
99					delete(map2, k)
100				}
101			}
102		}
103        itr.Next()
104    }
105	
106    doc.Save(outputPath + outputFilename, uint(SDFDocE_remove_unused))
107    doc.Close()
108    PDFNetTerminate()
109    fmt.Println("Done. Result saved in " + outputFilename +"...")
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.pdf.*;
7import com.pdftron.sdf.SDFDoc;
8import com.pdftron.common.PDFNetException;
9
10import java.util.*;
11
12import com.pdftron.sdf.Obj;
13
14//---------------------------------------------------------------------------------------
15// The sample code shows how to edit the page display list and how to modify graphics state 
16// attributes on existing Elements. In particular the sample program strips all images from 
17// the page, changes path fill color to red, and changes text color to blue. 
18//---------------------------------------------------------------------------------------
19public class ElementEditTest {
20    public static void processElements(ElementWriter writer, ElementReader reader, Set<Integer> visited)  throws PDFNetException {
21        Element element;
22		while ((element = reader.next()) != null) {
23			switch (element.getType()) {
24				case Element.e_image:
25				case Element.e_inline_image:
26					// remove all images by skipping them
27					break;
28				case Element.e_path: {
29					// Set all paths to red color.
30					GState gs = element.getGState();
31					gs.setFillColorSpace(ColorSpace.createDeviceRGB());
32					gs.setFillColor(new ColorPt(1, 0, 0));
33					writer.writeElement(element);
34				}
35				break;
36				case Element.e_text: {
37					// Set all text to blue color.
38					GState gs = element.getGState();
39					gs.setFillColorSpace(ColorSpace.createDeviceRGB());
40					gs.setFillColor(new ColorPt(0, 0, 1));
41					writer.writeElement(element);
42				}
43				break;
44				case Element.e_form: {
45					writer.writeElement(element); // write Form XObject reference to current stream
46					Obj form_obj = element.getXObject();
47					if (!visited.contains((int) form_obj.getObjNum())) // if this XObject has not been processed
48					{
49						// recursively process the Form XObject
50						visited.add((int) form_obj.getObjNum());
51						ElementWriter new_writer = new ElementWriter();
52						reader.formBegin();
53						new_writer.begin(form_obj);
54
55						reader.clearChangeList();
56						new_writer.setDefaultGState(reader);  
57
58						processElements(new_writer, reader, visited);
59						new_writer.end();
60						reader.end();
61					}
62				}
63				break;
64				default:
65					writer.writeElement(element);
66					break;
67			}
68		}
69  
70	}
71
72	public static void main(String[] args) {
73
74		PDFNet.initialize(PDFTronLicense.Key());
75
76		// Relative path to the folder containing test files.
77		String input_path = "../../TestFiles/";
78		String output_path = "../../TestFiles/Output/";
79		String input_filename = "newsletter.pdf";
80		String output_filename = "newsletter_edited.pdf";
81
82		System.out.println("Opening the input file...");
83		try (PDFDoc doc = new PDFDoc((input_path + input_filename))) {
84			doc.initSecurityHandler();
85
86			ElementWriter writer = new ElementWriter();
87			ElementReader reader = new ElementReader();
88			Set<Integer> visited = new TreeSet<Integer>();
89
90			PageIterator itr = doc.getPageIterator();
91			while (itr.hasNext()) {
92				try{
93					Page page = itr.next();
94					visited.add((int) page.getSDFObj().getObjNum());
95
96					reader.begin(page);
97					writer.begin(page, ElementWriter.e_replacement, false, true, page.getResourceDict());
98
99					processElements(writer, reader, visited);
100					writer.end();
101					reader.end();
102				} catch (Exception e) {
103					e.printStackTrace();
104				}
105			}
106
107			// Save modified document
108			doc.save(output_path + output_filename, SDFDoc.SaveMode.REMOVE_UNUSED, null);
109			System.out.println("Done. Result saved in " + output_filename + "...");
110		} catch (Exception e) {
111			e.printStackTrace();
112		}
113
114		PDFNet.terminate();
115	}
116}
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
7const { PDFNet } = require('@pdftron/pdfnet-node');
8const PDFTronLicense = require('../LicenseKey/LicenseKey');
9
10((exports) => {
11
12  exports.runElementEditTest = () => {
13
14    async function ProcessElements(reader, writer, visited) {
15      await PDFNet.startDeallocateStack();
16      const colorspace = await PDFNet.ColorSpace.createDeviceRGB();
17      const redColor = await PDFNet.ColorPt.init(1, 0, 0);
18      const blueColor = await PDFNet.ColorPt.init(0, 0, 1);
19
20      for (let element = await reader.next(); element !== null; element = await reader.next()) {
21        const elementType = await element.getType();
22        let gs;
23        let formObj;
24        let formObjNum = null;
25        switch (elementType) {
26          case PDFNet.Element.Type.e_image:
27          case PDFNet.Element.Type.e_inline_image:
28            // remove all images by skipping them
29            break;
30          case PDFNet.Element.Type.e_path:
31            // Set all paths to red
32            gs = await element.getGState();
33            gs.setFillColorSpace(colorspace);
34            await gs.setFillColorWithColorPt(redColor);
35            await writer.writeElement(element);
36            break;
37          case PDFNet.Element.Type.e_text:
38            // Set all text to blue
39            gs = await element.getGState();
40            gs.setFillColorSpace(colorspace);
41            await gs.setFillColorWithColorPt(blueColor);
42            await writer.writeElement(element);
43            break;
44          case PDFNet.Element.Type.e_form:
45            await writer.writeElement(element);
46            formObj = await element.getXObject();
47            formObjNum = await formObj.getObjNum();
48            // if XObject not yet processed
49            if (visited.indexOf(formObjNum) === -1) {
50              // Set Replacement
51              const insertedObj = await formObj.getObjNum();
52              if (!visited.includes(insertedObj)) {
53                visited.push(insertedObj);
54              }
55              const newWriter = await PDFNet.ElementWriter.create();
56              await reader.formBegin();
57              await newWriter.beginOnObj(formObj);
58              await ProcessElements(reader, newWriter, visited);
59              await newWriter.end();
60              await reader.end();
61            }
62            break;
63          default:
64            await writer.writeElement(element);
65        }
66      }
67      await PDFNet.endDeallocateStack();
68    }
69
70    const main = async () => {
71      // Relative path to the folder containing test files.
72      const inputPath = '../TestFiles/';
73      try {
74        console.log('Opening the input file...');
75        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'newsletter.pdf');
76        doc.initSecurityHandler();
77
78        const writer = await PDFNet.ElementWriter.create();
79        const reader = await PDFNet.ElementReader.create();
80        const visited = [];
81
82        const itr = await doc.getPageIterator(1);
83
84        // Process each page in the document
85        for (itr; await itr.hasNext(); itr.next()) {
86          const page = await itr.current();
87          const sdfObj = await page.getSDFObj();
88          const insertedObj = await sdfObj.getObjNum();
89          if (!visited.includes(insertedObj)) {
90            visited.push(insertedObj);
91          }
92          await reader.beginOnPage(page);
93          await writer.beginOnPage(page, PDFNet.ElementWriter.WriteMode.e_replacement, false, true, await page.getResourceDict());
94          await ProcessElements(reader, writer, visited);
95          await writer.end();
96          await reader.end();
97        }
98
99        await doc.save(inputPath + 'Output/newsletter_edited.pdf', PDFNet.SDFDoc.SaveOptions.e_remove_unused);
100        console.log('Done. Result saved in newsletter_edited.pdf...');
101      } catch (err) {
102        console.log(err);
103      }
104    };
105
106    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function (error) { console.log('Error: ' + JSON.stringify(error)); }).then(function () { return PDFNet.shutdown(); });
107  };
108  exports.runElementEditTest();
109})(exports);
110// eslint-disable-next-line spaced-comment
111//# sourceURL=ElementEditTest.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#---------------------------------------------------------------------------------------
11# The sample code shows how to edit the page display list and how to modify graphics state 
12# attributes on existing Elements. In particular the sample program strips all images from 
13# the page and changes text color to blue. 
14#---------------------------------------------------------------------------------------
15
16# Relative path to the folder containing the test files.
17$input_path = getcwd()."/../../TestFiles/";
18$output_path = $input_path."Output/";
19$input_filename = "newsletter.pdf";
20$output_filename = "newsletter_edited.pdf";
21
22function ProcessElements($reader, $writer, $map) {
23	while (($element = $reader->Next()) != null) 	// Read page contents
24	{
25		switch ($element->GetType())
26		{		
27		case Element::e_image: 
28		case Element::e_inline_image: 
29			// remove all images by skipping them
30			break;
31		case Element::e_path:
32			{
33				// Set all paths to red color.
34				$gs = $element->GetGState();
35				$gs->SetFillColorSpace(ColorSpace::CreateDeviceRGB());
36				$gs->SetFillColor(new ColorPt(1.0, 0.0, 0.0));
37				$writer->WriteElement($element);
38				break;
39			}
40		case Element::e_text:// Process text strings...
41			{
42				// Set all text to blue color.
43				$gs = $element->GetGState();
44				$gs->SetFillColorSpace(ColorSpace::CreateDeviceRGB());
45				$cp = new ColorPt(0.0, 0.0, 1.0);
46				$gs->SetFillColor($cp);
47				$writer->WriteElement($element);
48				break;
49			}
50		case Element::e_form:// Recursively process form XObjects
51			{
52				$o = $element->GetXObject();
53				$objNum = $o->GetObjNum();
54				$map[$objNum] = $o;
55				$writer->WriteElement($element);
56				break; 
57			}
58		default:
59			$writer->WriteElement($element);
60		}
61	}
62}
63
64	PDFNet::Initialize($LicenseKey);
65	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.
66	
67
68	// Open the test file
69	echo nl2br("Opening the input file...\n");
70	$doc = new PDFDoc($input_path.$input_filename);
71	$doc->InitSecurityHandler();
72
73	$writer = new ElementWriter();
74	$reader = new ElementReader();
75	
76	$itr = $doc->GetPageIterator();
77
78	while ($itr->HasNext())
79	{
80		$page = $itr->Current();
81		$reader->Begin($page);
82		$writer->Begin($page, ElementWriter::e_replacement, false);
83		$map1 = array();
84		ProcessElements($reader, $writer, $map1);
85		$writer->End();
86		$reader->End();
87		
88		$map2 = array();
89		while (!(empty($map1) && empty($map2)))
90		{
91			foreach ($map1 as $k=>$v)
92			{
93				$obj = $v;
94				$writer->Begin($obj);
95				$reader->Begin($obj, $page->GetResourceDict());
96				ProcessElements($reader, $writer, $map2);
97				$reader->End();
98				$writer->End();
99
100				unset($map1[$k]);
101			}
102			if (empty($map1) && !empty($map2))
103			{
104				$map1 = $map1 + $map2;
105				$map2 = array();
106			}
107		}
108		$itr->Next();
109	}
110
111	$doc->Save($output_path.$output_filename, SDFDoc::e_remove_unused);	
112	PDFNet::Terminate();	
113	echo nl2br("Done. Result saved in ".$output_filename."...\n");
114?>
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# The sample code shows how to edit the page display list and how to modify graphics state 
16# attributes on existing Elements. In particular the sample program strips all images from 
17# the page, changes path fill color to red, and changes text color to blue. 
18#---------------------------------------------------------------------------------------
19
20def ProcessElements(reader, writer, map):
21    element = reader.Next()     # Read page contents
22    while element != None:
23        type = element.GetType()
24        if type == Element.e_image:
25            # remove all images by skipping them
26            pass
27        elif type == Element.e_inline_image:            
28            # remove all images by skipping them
29            pass
30        elif type == Element.e_path:
31            # Set all paths to red color.
32            gs = element.GetGState()
33            gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
34            gs.SetFillColor(ColorPt(1, 0, 0))
35            writer.WriteElement(element)
36        elif type == Element.e_text:    # Process text strings...
37            # Set all text to blue color.
38            gs = element.GetGState()
39            gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
40            cp = ColorPt(0, 0, 1)
41            gs.SetFillColor(cp)
42            writer.WriteElement(element)
43        elif type == Element.e_form:    # Recursively process form XObjects
44            o = element.GetXObject()
45            map[o.GetObjNum()] = o
46            writer.WriteElement(element)
47        else:
48            writer.WriteElement(element)
49        element = reader.Next()
50
51def main():
52    PDFNet.Initialize(LicenseKey)
53    
54    # Relative path to the folder containing the test files.
55    input_path = "../../TestFiles/"
56    output_path = "../../TestFiles/Output/"
57    input_filename = "newsletter.pdf"
58    output_filename = "newsletter_edited.pdf"
59    
60    
61    # Open the test file
62    print("Opening the input file...")
63    doc = PDFDoc(input_path + input_filename)
64    doc.InitSecurityHandler()
65    
66    writer = ElementWriter()
67    reader = ElementReader()
68    
69    itr = doc.GetPageIterator()
70    
71    while itr.HasNext():
72        page = itr.Current()
73        reader.Begin(page)
74        writer.Begin(page, ElementWriter.e_replacement, False)
75        map1 = {}
76        ProcessElements(reader, writer, map1)
77        writer.End()
78        reader.End()
79		
80        map2 = {}
81        while (map1 or map2):
82            for k in map1.keys():
83                obj = map1[k]
84                writer.Begin(obj)
85                reader.Begin(obj, page.GetResourceDict())
86                ProcessElements(reader, writer, map2)
87                reader.End()
88                writer.End()
89
90                del map1[k]
91            if (not map1 and map2):
92                map1.update(map2)
93                map2.clear()
94        itr.Next()
95        
96    doc.Save(output_path + output_filename, SDFDoc.e_remove_unused)
97    doc.Close()
98    PDFNet.Terminate()
99    print("Done. Result saved in " + output_filename +"...")
100    
101if __name__ == '__main__':
102    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# The sample code shows how to edit the page display list and how to modify graphics state 
14# attributes on existing Elements. In particular the sample program strips all images from 
15# the page and changes text color to blue. 
16#---------------------------------------------------------------------------------------
17
18def ProcessElements(reader, writer, map)
19	element = reader.Next()	 # Read page contents
20	while !element.nil? do
21		type = element.GetType()
22		case type
23		when Element::E_image
24		# remove all images by skipping them
25		when Element::E_inline_image	
26			# remove all images by skipping them
27		when Element::E_path
28			# Set all paths to red color.
29			gs = element.GetGState()
30			gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
31			gs.SetFillColor(ColorPt.new(1, 0, 0))
32			writer.WriteElement(element)
33		when Element::E_text	# Process text strings...
34			# Set all text to blue color.
35			gs = element.GetGState()
36			gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
37			cp = ColorPt.new(0, 0, 1)
38			gs.SetFillColor(cp)
39			writer.WriteElement(element)
40		when Element::E_form	# Recursively process form XObjects
41			o = element.GetXObject()
42			map[o.GetObjNum()] = o
43			writer.WriteElement(element)
44		else
45			writer.WriteElement(element)
46		end
47		element = reader.Next()
48	end
49end
50
51	PDFNet.Initialize(PDFTronLicense.Key)
52	
53	# Relative path to the folder containing the test files.
54	input_path = "../../TestFiles/"
55	output_path = "../../TestFiles/Output/"
56	input_filename = "newsletter.pdf"
57	output_filename = "newsletter_edited.pdf"
58	
59	
60	# Open the test file
61	puts "Opening the input file..."
62	doc = PDFDoc.new(input_path + input_filename)
63	doc.InitSecurityHandler()
64	
65	writer = ElementWriter.new()
66	reader = ElementReader.new()
67	
68	itr = doc.GetPageIterator()
69	
70	while itr.HasNext() do
71		page = itr.Current()
72		reader.Begin(page)
73		writer.Begin(page, ElementWriter::E_replacement, false)
74		map1 = {}
75		ProcessElements(reader, writer, map1)
76		writer.End()
77		reader.End()
78		
79		map2 = {}
80		while (not(map1.empty? and map2.empty?)) do
81			map1.each do |k, v|
82				obj = v
83				writer.Begin(obj)
84				reader.Begin(obj, page.GetResourceDict())
85				ProcessElements(reader, writer, map2)
86				reader.End()
87				writer.End()
88
89				map1.delete(k)
90			end
91			if (map1.empty? and not map2.empty?)
92				map1.update(map2)
93				map2.clear
94			end
95		end
96		itr.Next()
97	end
98		
99	doc.Save(output_path + output_filename, SDFDoc::E_remove_unused)
100	doc.Close()
101	PDFNet.Terminate
102	puts "Done. Result saved in " + output_filename + "..."
1'
2' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3'
4
5Imports System
6Imports System.Collections.Generic
7
8Imports pdftron
9Imports pdftron.Common
10Imports pdftron.Filters
11Imports pdftron.SDF
12Imports pdftron.PDF
13
14Imports XSet = System.Collections.Generic.List(Of Integer)
15
16Module ElementEditTestVB
17    Dim pdfNetLoader As PDFNetLoader
18    Sub New()
19        pdfNetLoader = pdftron.PDFNetLoader.Instance()
20    End Sub
21
22    ' The sample code shows how to edit the page display list and how to modify graphics state 
23    ' attributes on existing Elements. In particular the sample program strips all images from 
24    ' the page, changes the path fill color to red, and changes text color to blue. 
25
26    Sub ProcessElements(ByVal reader As ElementReader, ByVal writer As ElementWriter, ByVal visited As XSet)
27        Dim element As Element = reader.Next()
28        While Not IsNothing(element) ' Read page contents
29            If element.GetType() = element.Type.e_image Then
30                ' remove all images by skipping them
31                element = reader.Next()
32            ElseIf element.GetType() = element.Type.e_inline_image Then
33                ' remove all images by skipping them
34                element = reader.Next()
35            ElseIf element.GetType() = element.Type.e_path Then
36                ' Set all paths to red color.
37                Dim gs As GState = element.GetGState()
38                gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
39                gs.SetFillColor(New ColorPt(1, 0, 0))
40                writer.WriteElement(element)
41                element = reader.Next()
42            ElseIf element.GetType() = element.Type.e_text Then
43                ' Set all text to blue color.
44                Dim gs As GState = element.GetGState()
45                gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB())
46                gs.SetFillColor(New ColorPt(0, 0, 1))
47                writer.WriteElement(element)
48                element = reader.Next()
49            ElseIf element.GetType() = element.Type.e_form Then
50                writer.WriteElement(element) ' write Form XObject reference to current stream
51
52                Dim form_obj As Obj = element.GetXObject()
53                If Not visited.Contains(form_obj.GetObjNum()) Then ' if this XObject has not been processed
54                    ' recursively process the Form XObject
55                    visited.Add(form_obj.GetObjNum())
56                    Dim new_writer As ElementWriter = New ElementWriter
57                    reader.FormBegin()
58                    new_writer.Begin(form_obj, True)
59
60                    reader.ClearChangeList()
61                    new_writer.SetDefaultGState(reader)
62
63                    ProcessElements(reader, new_writer, visited)
64                    new_writer.End()
65                    reader.End()
66                End If
67            Else
68                writer.WriteElement(element)
69                element = reader.Next()
70            End If
71        End While
72    End Sub
73
74    Sub Main()
75
76        PDFNet.Initialize(PDFTronLicense.Key)
77
78        ' Relative path to the folder containing test files.
79        Dim input_path As String = "../../../../TestFiles/"
80        Dim output_path As String = "../../../../TestFiles/Output/"
81        Dim input_filename As String = "newsletter.pdf"
82        Dim output_filename As String = "newsletter_edited.pdf"
83
84        Try
85
86            Console.WriteLine("Opening the input file...")
87            Using doc As PDFDoc = New PDFDoc(input_path + input_filename)
88                doc.InitSecurityHandler()
89
90                Dim writer As ElementWriter = New ElementWriter
91                Dim reader As ElementReader = New ElementReader
92                Dim visited As XSet = New XSet()
93
94                Dim itr As PageIterator = doc.GetPageIterator()
95
96                While itr.HasNext()
97                    Try
98                        Dim page As Page = itr.Current()
99                        visited.Add(page.GetSDFObj().GetObjNum())
100
101                        reader.Begin(page)
102                        writer.Begin(page, ElementWriter.WriteMode.e_replacement, False, True, page.GetResourceDict())
103                        
104                        ProcessElements(reader, writer, visited)
105                        writer.End()
106                        reader.End()
107
108                        itr.Next()
109                    Catch e As PDFNetException
110                        Console.WriteLine(e.Message)
111                    End Try
112                End While
113
114
115                doc.Save(output_path + output_filename, SDF.SDFDoc.SaveOptions.e_remove_unused)
116            End Using
117            Console.WriteLine("Done. Result saved in {0}...", output_filename)
118        Catch e As PDFNetException
119            Console.WriteLine(e.Message)
120        End Try
121        PDFNet.Terminate()
122    End Sub
123
124End Module
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales