Sample C# code for using Apryse SDK to read/write a PDF document from/to memory buffer. This is useful for applications that work with dynamic PDFdocuments that don't need to be saved/read from a disk. Learn more about our Server SDK.
1//
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3//
4
5using System;
6using System.IO;
7using pdftron;
8using pdftron.Common;
9using pdftron.Filters;
10using pdftron.SDF;
11using pdftron.PDF;
12
13// The following sample illustrates how to read/write a PDF document from/to
14// a memory buffer. This is useful for applications that work with dynamic PDF
15// documents that don't need to be saved/read from a disk.
16namespace PDFDocMemoryTestCS
17{
18 class Class1
19 {
20 private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
21 static Class1() {}
22
23 [STAThread]
24 static void Main(string[] args)
25 {
26 PDFNet.Initialize(PDFTronLicense.Key);
27
28 // Relative path to the folder containing test files.
29 string input_path = "../../../../TestFiles/";
30 string output_path = "../../../../TestFiles/Output/";
31
32 try
33 {
34 // Read a PDF document from a stream or pass-in a memory buffer...
35 FileStream istm = new FileStream(input_path + "tiger.pdf", FileMode.Open, FileAccess.Read);
36 using (PDFDoc doc = new PDFDoc(istm))
37 using (ElementWriter writer = new ElementWriter())
38 using (ElementReader reader = new ElementReader())
39 {
40 doc.InitSecurityHandler();
41
42 int num_pages = doc.GetPageCount();
43
44 Element element;
45
46 // Perform some document editing ...
47 // Here we simply copy all elements from one page to another.
48 for(int i = 1; i <= num_pages; ++i)
49 {
50 Page pg = doc.GetPage(2 * i - 1);
51
52 reader.Begin(pg);
53 Page new_page = doc.PageCreate(pg.GetMediaBox());
54 doc.PageInsert(doc.GetPageIterator(2*i), new_page);
55
56 writer.Begin(new_page);
57 while ((element = reader.Next()) != null) // Read page contents
58 {
59 writer.WriteElement(element);
60 }
61
62 writer.End();
63 reader.End();
64 }
65
66 doc.Save(output_path + "doc_memory_edit.pdf", SDFDoc.SaveOptions.e_remove_unused);
67
68 // Save the document to a stream or a memory buffer...
69 using (FileStream ostm = new FileStream(output_path + "doc_memory_edit.txt", FileMode.Create, FileAccess.Write)) {
70 doc.Save(ostm, SDFDoc.SaveOptions.e_remove_unused);
71 }
72
73 // Read some data from the file stored in memory
74 reader.Begin(doc.GetPage(1));
75 while ((element = reader.Next()) != null) {
76 if (element.GetType() == Element.Type.e_path)
77 Console.Write("Path, ");
78 }
79 reader.End();
80
81 Console.WriteLine("");
82 Console.WriteLine("");
83 Console.WriteLine("Done. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...");
84 }
85 }
86 catch (PDFNetException e)
87 {
88 Console.WriteLine(e.Message);
89 }
90 PDFNet.Terminate();
91 }
92 }
93}
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 <Filters/MappedFile.h>
9#include <Filters/FilterReader.h>
10#include <Filters/FilterWriter.h>
11#include <PDF/ElementWriter.h>
12#include <PDF/ElementReader.h>
13
14#include <iostream>
15#include <fstream>
16#include "../../LicenseKey/CPP/LicenseKey.h"
17
18using namespace std;
19using namespace pdftron;
20using namespace SDF;
21using namespace PDF;
22using namespace Filters;
23
24int main(int argc, char *argv[])
25{
26 int ret = 0;
27 PDFNet::Initialize(LicenseKey);
28
29 // Relative path to the folder containing test files.
30 string input_path = "../../TestFiles/";
31 string output_path = "../../TestFiles/Output/";
32
33
34 // The following sample illustrates how to read/write a PDF document from/to
35 // a memory buffer. This is useful for applications that work with dynamic PDF
36 // documents that don't need to be saved/read from a disk.
37 try
38 {
39 // Read a PDF document in a memory buffer.
40 MappedFile file((input_path + "tiger.pdf"));
41 size_t file_sz = file.FileSize();
42
43 FilterReader file_reader(file);
44
45 unsigned char* mem = new unsigned char[file_sz];
46 file_reader.Read((unsigned char*)mem, file_sz);
47 PDFDoc doc(mem, file_sz);
48 delete[] mem;
49
50 doc.InitSecurityHandler();
51 int num_pages = doc.GetPageCount();
52
53 ElementWriter writer;
54 ElementReader reader;
55 Element element;
56
57 // Create a duplicate of every page but copy only path objects
58 for(int i=1; i<=num_pages; ++i)
59 {
60 PageIterator itr = doc.GetPageIterator(2*i-1);
61
62 reader.Begin(itr.Current());
63 Page new_page = doc.PageCreate(itr.Current().GetMediaBox());
64 PageIterator next_page = itr;
65 next_page.Next();
66 doc.PageInsert(next_page, new_page );
67
68 writer.Begin(new_page);
69 while ((element = reader.Next()) !=0) // Read page contents
70 {
71 //if (element.GetType() == Element::e_path)
72 writer.WriteElement(element);
73 }
74
75 writer.End();
76 reader.End();
77 }
78
79 doc.Save((output_path + "doc_memory_edit.pdf").c_str(), SDFDoc::e_remove_unused, NULL);
80 // doc.Save((output_path + "doc_memory_edit.pdf").c_str(), Doc::e_linearized, NULL);
81
82 // Save the document to a memory buffer.
83 const char* buf = 0;
84 size_t buf_sz;
85
86 doc.Save(buf, buf_sz, SDFDoc::e_remove_unused, NULL);
87 // doc.Save(buf, buf_sz, Doc::e_linearized, NULL);
88
89 // Write the contents of the buffer to the disk
90 {
91 ofstream out((output_path + "doc_memory_edit.txt").c_str(), ofstream::binary);
92 out.write(buf, buf_sz);
93 out.close();
94 }
95
96 // Read some data from the file stored in memory
97 reader.Begin(doc.GetPage(1));
98 while ((element = reader.Next()) !=0) {
99 if (element.GetType() == Element::e_path) cout << "Path, ";
100 }
101 reader.End();
102
103 cout << "\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ..." << endl;
104 }
105 catch(Common::Exception& e)
106 {
107 cout << e << endl;
108 ret = 1;
109 }
110 catch(...)
111 {
112 cout << "Unknown Exception" << endl;
113 ret = 1;
114 }
115
116 PDFNet::Terminate();
117 return ret;
118}
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 "os"
10 . "pdftron"
11)
12
13import "pdftron/Samples/LicenseKey/GO"
14
15func main(){
16 PDFNetInitialize(PDFTronLicense.Key)
17
18 // Relative path to the folder containing the test files.
19 inputPath := "../../TestFiles/"
20 outputPath := "../../TestFiles/Output/"
21
22 // The following sample illustrates how to read/write a PDF document from/to
23 // a memory buffer. This is useful for applications that work with dynamic PDF
24 // documents that don't need to be saved/read from a disk.
25
26 // Read a PDF document in a memory buffer.
27 file := NewMappedFile(inputPath + "tiger.pdf")
28 fileSZ := file.FileSize()
29
30 fileReader := NewFilterReader(file)
31
32 mem := fileReader.Read(fileSZ)
33 memBytes := make([]byte, int(mem.Size()))
34 for i := 0; i < int(mem.Size()); i++{
35 memBytes[i] = mem.Get(i)
36 }
37 doc := NewPDFDoc(&memBytes[0], fileSZ)
38 doc.InitSecurityHandler()
39 numPages := doc.GetPageCount()
40
41 writer := NewElementWriter()
42 reader := NewElementReader()
43 element := NewElement()
44
45 // Create a duplicate of every page but copy only path objects
46
47 i := 1
48 for i <= numPages{
49 itr := doc.GetPageIterator(uint(2*i - 1))
50
51 reader.Begin(itr.Current())
52 new_page := doc.PageCreate(itr.Current().GetMediaBox())
53 next_page := itr
54 next_page.Next()
55 doc.PageInsert(next_page, new_page)
56
57 writer.Begin(new_page)
58 element = reader.Next()
59 for element.GetMp_elem().Swigcptr() != 0 { // Read page contents
60 //if element.GetType() == Element.e_path:
61 writer.WriteElement(element)
62 element = reader.Next()
63 }
64 writer.End()
65 reader.End()
66 i = i + 1
67 }
68 doc.Save(outputPath + "doc_memory_edit.pdf", uint(SDFDocE_remove_unused))
69
70 // Save the document to a memory buffer
71 buffer := (doc.Save(uint(SDFDocE_remove_unused))).(VectorUnChar)
72
73 // Write the contents of the buffer to the disk
74 bufferBytes := make([]byte, int(buffer.Size()))
75 for i := 0; i < int(buffer.Size()); i++{
76 bufferBytes[i] = buffer.Get(i)
77 }
78 f, err := os.Create(outputPath + "doc_memory_edit.txt")
79
80 if err != nil {
81 fmt.Println(err)
82 }
83 defer f.Close()
84 _, err2 := f.Write(bufferBytes)
85 if err2 != nil {
86 fmt.Println(err2)
87 }
88
89 // Read some data from the file stored in memory
90 reader.Begin(doc.GetPage(1))
91 element = reader.Next()
92 for element.GetMp_elem().Swigcptr() != 0{
93 if element.GetType() == ElementE_path{
94 os.Stdout.Write([]byte("Path, "))
95 }
96 element = reader.Next()
97 }
98 reader.End()
99
100 PDFNetTerminate()
101 fmt.Println("\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...")
102}
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 java.io.File;
7import java.io.FileInputStream;
8import java.io.FileNotFoundException;
9import java.io.FileOutputStream;
10import java.io.IOException;
11
12import com.pdftron.common.PDFNetException;
13import com.pdftron.filters.FilterReader;
14import com.pdftron.filters.FilterWriter;
15import com.pdftron.filters.MappedFile;
16import com.pdftron.pdf.*;
17import com.pdftron.sdf.SDFDoc;
18
19public class PDFDocMemoryTest {
20
21 public static void main(String[] args) {
22
23 PDFNet.initialize(PDFTronLicense.Key());
24
25 // Relative path to the folder containing test files.
26 String input_path = "../../TestFiles/";
27 String output_path = "../../TestFiles/Output/";
28
29 // The following sample illustrates how to read/write a PDF document from/to
30 // a memory buffer. This is useful for applications that work with dynamic PDF
31 // documents that don't need to be saved/read from a disk.
32 try {
33 // Read a PDF document in a memory buffer.
34 MappedFile file = new MappedFile((input_path + "tiger.pdf"));
35 long file_sz = file.fileSize();
36
37 FilterReader file_reader = new FilterReader(file);
38
39 byte[] mem = new byte[(int) file_sz];
40
41 long bytes_read = file_reader.read(mem);
42 try (PDFDoc doc = new PDFDoc(mem)) {
43
44 doc.initSecurityHandler();
45 int num_pages = doc.getPageCount();
46
47 ElementWriter writer = new ElementWriter();
48 ElementReader reader = new ElementReader();
49 Element element;
50
51 // Create a duplicate of every page but copy only path objects
52
53 for (int i = 1; i <= num_pages; ++i) {
54 PageIterator itr = doc.getPageIterator(2 * i - 1);
55 Page current = itr.next();
56 reader.begin(current);
57 Page new_page = doc.pageCreate(current.getMediaBox());
58 doc.pageInsert(itr, new_page);
59
60 writer.begin(new_page);
61 while ((element = reader.next()) != null) // Read page contents
62 {
63 //if (element.getType() == Element.e_path)
64 writer.writeElement(element);
65 }
66
67 writer.end();
68 reader.end();
69 }
70
71 doc.save(output_path + "doc_memory_edit.pdf", SDFDoc.SaveMode.REMOVE_UNUSED, null);
72
73 // Save the document to a memory buffer.
74
75
76 byte[] buf = doc.save(SDFDoc.SaveMode.REMOVE_UNUSED, null);
77 // doc.Save(buf, buf_sz, Doc::e_linearized, NULL);
78
79 // Write the contents of the buffer to the disk
80 {
81 File outfile = new File(output_path + "doc_memory_edit.txt");
82 // output "doc_memory_edit.txt"
83 FileOutputStream fop = new FileOutputStream(outfile);
84 if (!outfile.exists()) {
85 outfile.createNewFile();
86 }
87 fop.write(buf);
88 fop.flush();
89 fop.close();
90 }
91
92 // Read some data from the file stored in memory
93 reader.begin(doc.getPage(1));
94 while ((element = reader.next()) != null) {
95 if (element.getType() == Element.e_path) System.out.print("Path, ");
96 }
97 reader.end();
98
99 System.out.println("\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...");
100 }
101 }
102 catch (PDFNetException e)
103 {
104 e.printStackTrace();
105 System.out.println(e);
106 }
107 catch (Exception e)
108 {
109 e.printStackTrace();
110 }
111 PDFNet.terminate();
112 }
113}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6const fs = require('fs');
7const { PDFNet } = require('@pdftron/pdfnet-node');
8const PDFTronLicense = require('../LicenseKey/LicenseKey');
9
10((exports) => {
11 'use strict';
12
13 exports.runPDFDocMemoryTest = () => {
14 const main = async () => {
15 const outputPath = '../TestFiles/Output/';
16
17 // The following sample illustrates how to read/write a PDF document from/to
18 // a memory buffer. This is useful for applications that work with dynamic PDF
19 // documents that don't need to be saved/read from a disk.
20 try {
21 // Read a PDF document in a memory buffer.
22 const file = await PDFNet.Filter.createMappedFileFromUString('../TestFiles/tiger.pdf');
23 const file_sz = await file.mappedFileFileSize();
24
25 const file_reader = await PDFNet.FilterReader.create(file);
26
27 const mem = await file_reader.read(file_sz);
28 const doc = await PDFNet.PDFDoc.createFromBuffer(mem);
29
30 doc.initSecurityHandler();
31 const num_pages = await doc.getPageCount();
32
33 const writer = await PDFNet.ElementWriter.create();
34 const reader = await PDFNet.ElementReader.create();
35
36 // Create a duplicate of every page but copy only path objects
37 for (let i = 1; i <= num_pages; ++i) {
38 const itr = await doc.getPageIterator(2 * i - 1);
39
40 const cur_page = await itr.current();
41 reader.beginOnPage(cur_page);
42 const new_page = await doc.pageCreate(await cur_page.getMediaBox());
43 itr.next();
44 doc.pageInsert(itr, new_page);
45
46 writer.beginOnPage(new_page);
47 var element;
48 while (element = await reader.next()) { // Read page contents
49 writer.writeElement(element);
50 }
51
52 await writer.end();
53 await reader.end();
54 }
55
56 doc.save(outputPath + 'doc_memory_edit.pdf', PDFNet.SDFDoc.SaveOptions.e_remove_unused);
57
58 // Save the document to a memory buffer.
59 const docbuf = await doc.saveMemoryBuffer(PDFNet.SDFDoc.SaveOptions.e_remove_unused);
60
61 // Write the contents of the buffer to the disk
62 fs.appendFileSync(outputPath + 'doc_memory_edit.txt', docbuf);
63
64 let dataStr = ''
65 // Read some data from the file stored in memory
66 reader.beginOnPage(await doc.getPage(1));
67 while (element = await reader.next()) {
68 if (await element.getType() == PDFNet.Element.Type.e_path) dataStr += 'Path, ';
69 }
70 reader.end();
71 console.log(dataStr);
72
73 console.log('\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...');
74 } catch (err) {
75 console.log(err);
76 }
77 }
78 PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error) {
79 console.log('Error: ' + JSON.stringify(error));
80 }).then(function(){ return PDFNet.shutdown(); });
81 };
82 exports.runPDFDocMemoryTest();
83})(exports);
84// eslint-disable-next-line spaced-comment
85//# sourceURL=PDFDocMemoryTest.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 // The following sample illustrates how to read/write a PDF document from/to
15 // a memory buffer. This is useful for applications that work with dynamic PDF
16 // documents that don't need to be saved/read from a disk.
17
18 PDFNet::Initialize($LicenseKey);
19 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.
20
21 // Read a PDF document in a memory buffer.
22 $file = new MappedFile($input_path."tiger.pdf");
23 $file_sz = $file->FileSize();
24
25 $file_reader = new FilterReader($file);
26 $mem = $file_reader->Read($file_sz);
27 $test = array();
28 for ($i = 0; $i < strlen($mem); $i++) {
29 $test[] = ord($mem[$i]);
30 }
31 $doc = new PDFDoc($mem, $file_sz);
32 $doc->InitSecurityHandler();
33 $num_pages = $doc->GetPageCount();
34
35 $writer = new ElementWriter();
36 $reader = new ElementReader();
37
38 // Create a duplicate of every page but copy only path objects
39 for($i=1; $i<=$num_pages; ++$i)
40 {
41 $itr = $doc->GetPageIterator(2*$i-1);
42
43 $reader->Begin($itr->Current());
44 $new_page = $doc->PageCreate($itr->Current()->GetMediaBox());
45 $next_page = $itr;
46 $next_page->Next();
47 $doc->PageInsert($next_page, $new_page);
48
49 $writer->Begin($new_page);
50 while (($element = $reader->Next()) !=null) // Read page contents
51 {
52 //if ($element->GetType() == Element::e_path)
53 $writer->WriteElement($element);
54 }
55
56 $writer->End();
57 $reader->End();
58 }
59
60 $doc->Save($output_path."doc_memory_edit.pdf", SDFDoc::e_remove_unused);
61
62 // Save the document to a memory buffer.
63 $buffer = $doc->Save(SDFDoc::e_remove_unused);
64
65 // Write the contents of the buffer to the disk
66 $outfile = fopen($output_path."doc_memory_edit.txt", "w");
67 fwrite($outfile, $buffer);
68 fclose($outfile);;
69
70 // Read some data from the file stored in memory
71 $reader->Begin($doc->GetPage(1));
72 while (($element = $reader->Next()) !=null) {
73 if ($element->GetType() == Element::e_path) echo "Path, ";
74 }
75 $reader->End();
76 PDFNet::Terminate();
77 echo nl2br("\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...\n");
78?>
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
14def main():
15 PDFNet.Initialize(LicenseKey)
16
17 # Relative path to the folder containing the test files.
18 input_path = "../../TestFiles/"
19 output_path = "../../TestFiles/Output/"
20
21 # The following sample illustrates how to read/write a PDF document from/to
22 # a memory buffer. This is useful for applications that work with dynamic PDF
23 # documents that don't need to be saved/read from a disk.
24
25 # Read a PDF document in a memory buffer.
26 file = MappedFile(input_path + "tiger.pdf")
27 file_sz = file.FileSize()
28
29 file_reader = FilterReader(file)
30
31 mem = file_reader.Read(file_sz)
32 doc = PDFDoc(bytearray(mem), file_sz)
33 doc.InitSecurityHandler()
34 num_pages = doc.GetPageCount()
35
36 writer = ElementWriter()
37 reader = ElementReader()
38 element = Element()
39
40 # Create a duplicate of every page but copy only path objects
41
42 i = 1
43 while i <= num_pages:
44 itr = doc.GetPageIterator(2*i - 1)
45
46 reader.Begin(itr.Current())
47 new_page = doc.PageCreate(itr.Current().GetMediaBox())
48 next_page = itr
49 next_page.Next()
50 doc.PageInsert(next_page, new_page)
51
52 writer.Begin(new_page)
53 element = reader.Next()
54 while element != None: # Read page contents
55 #if element.GetType() == Element.e_path:
56 writer.WriteElement(element)
57 element = reader.Next()
58 writer.End()
59 reader.End()
60 i = i + 1
61
62 doc.Save(output_path + "doc_memory_edit.pdf", SDFDoc.e_remove_unused)
63
64 # Save the document to a memory buffer
65 buffer = doc.Save(SDFDoc.e_remove_unused)
66
67 # Write the contents of the buffer to the disk
68 if sys.version_info.major >= 3:
69 f = open(output_path + "doc_memory_edit.txt", "w")
70 else:
71 f = open(output_path + "doc_memory_edit.txt", "wb")
72 try:
73 f.write(str(buffer))
74 finally:
75 f.close()
76
77 # Read some data from the file stored in memory
78 reader.Begin(doc.GetPage(1))
79 element = reader.Next()
80 while element != None:
81 if element.GetType() == Element.e_path:
82 sys.stdout.write("Path, ")
83 element = reader.Next()
84 reader.End()
85
86 PDFNet.Terminate()
87 print("\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...")
88
89if __name__ == '__main__':
90 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# The following sample illustrates how to read/write a PDF document from/to
13# a memory buffer. This is useful for applications that work with dynamic PDF
14# documents that don't need to be saved/read from a disk.
15
16 PDFNet.Initialize(PDFTronLicense.Key)
17
18 # Relative path to the folder containing the test files.
19 input_path = "../../TestFiles/"
20 output_path = "../../TestFiles/Output/"
21
22 # Read a PDF document in a memory buffer.
23 file = MappedFile.new((input_path + "tiger.pdf"))
24 file_sz = file.FileSize
25
26 file_reader = FilterReader.new(file)
27
28 mem = file_reader.Read(file_sz)
29 doc = PDFDoc.new(mem, file_sz)
30 doc.InitSecurityHandler
31 num_pages = doc.GetPageCount
32
33 writer = ElementWriter.new
34 reader = ElementReader.new
35 element = Element.new
36
37 # Create a duplicate of every page but copy only path objects
38
39 i = 1
40 while i <= num_pages do
41 itr = doc.GetPageIterator(2*i - 1)
42
43 reader.Begin(itr.Current)
44 new_page = doc.PageCreate(itr.Current.GetMediaBox)
45 next_page = itr
46 next_page.Next
47 doc.PageInsert(next_page, new_page)
48
49 writer.Begin(new_page)
50 element = reader.Next
51 while !element.nil? do # Read page contents
52 #if element.GetType == Element::E_path
53 writer.WriteElement(element)
54 #end
55 element = reader.Next
56 end
57 writer.End
58 reader.End
59 i = i + 1
60 end
61
62 doc.Save(output_path + "doc_memory_edit.pdf", SDFDoc::E_remove_unused)
63
64 # Save the document to a memory buffer
65 buffer = doc.Save(SDFDoc::E_remove_unused)
66
67 # Write the contents of the buffer to the disk
68 File.open(output_path + "doc_memory_edit.txt", 'w') { |file| file.write(buffer) }
69
70 # Read some data from the file stored in memory
71 reader.Begin(doc.GetPage(1))
72 element = reader.Next
73 while !element.nil? do
74 if element.GetType == Element::E_path
75 print "Path, "
76 end
77 element = reader.Next
78 end
79 reader.End
80 PDFNet.Terminate
81 puts "\n\nDone. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ..."
1'
2' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3'
4
5Imports System
6Imports System.IO
7
8Imports pdftron
9Imports pdftron.Common
10Imports pdftron.Filters
11Imports pdftron.SDF
12Imports pdftron.PDF
13
14' The following sample illustrates how to read/write a PDF document from/to
15' a memory buffer. This is useful for applications that work with dynamic PDF
16' documents that don't need to be saved/read from a disk.
17Module PDFDocMemoryTestVB
18 Dim pdfNetLoader As PDFNetLoader
19 Sub New()
20 pdfNetLoader = pdftron.PDFNetLoader.Instance()
21 End Sub
22
23 Sub Main()
24
25 PDFNet.Initialize(PDFTronLicense.Key)
26
27 ' Relative path to the folder containing test files.
28 Dim input_path As String = "../../../../TestFiles/"
29 Dim output_path As String = "../../../../TestFiles/Output/"
30
31 Try
32 ' Read a PDF document in a memory buffer.
33 Dim istm As FileStream = New FileStream(input_path + "tiger.pdf", FileMode.Open, FileAccess.Read)
34 Using doc As PDFDoc = New PDFDoc(istm)
35 doc.InitSecurityHandler()
36 Dim num_pages As Integer = doc.GetPageCount()
37
38 Using writer As ElementWriter = New ElementWriter
39 Using reader As ElementReader = New ElementReader
40 Dim element As Element
41
42 ' Perform some document editing ...
43 ' Here we simply copy all elements from one page to another.
44 Dim i As Integer
45 For i = 1 To num_pages Step 1
46 Dim pg As Page = doc.GetPage(2 * i - 1)
47 reader.Begin(pg)
48 Dim new_page As Page = doc.PageCreate(pg.GetMediaBox())
49 doc.PageInsert(doc.GetPageIterator(2 * i), new_page)
50
51 writer.Begin(new_page)
52 element = reader.Next()
53 While (Not IsNothing(element)) ' Read page contents
54 writer.WriteElement(element)
55 element = reader.Next()
56 End While
57
58 writer.End()
59 reader.End()
60 Next i
61
62 doc.Save(output_path + "doc_memory_edit.pdf", SDF.SDFDoc.SaveOptions.e_remove_unused)
63
64 ' Save the document to a stream or a memory buffer...
65 Dim ostm As FileStream = New FileStream(output_path + "doc_memory_edit.txt", FileMode.Create, FileAccess.Write)
66 doc.Save(ostm, SDF.SDFDoc.SaveOptions.e_remove_unused)
67 ostm.Close()
68
69 ' Read some data from the file stored in memory
70 reader.Begin(doc.GetPage(1))
71 element = reader.Next()
72 While (Not IsNothing(element)) ' Read page contents
73 If element.GetType() = element.Type.e_path Then
74 Console.Write("Path, ")
75 End If
76
77 element = reader.Next()
78 End While
79 reader.End()
80 End Using
81 End Using
82 End Using
83 Console.WriteLine("")
84 Console.WriteLine("")
85 Console.WriteLine("Done. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...")
86 Catch ex As PDFNetException
87 Console.WriteLine(ex.Message)
88 Catch ex As Exception
89 MsgBox(ex.Message)
90 End Try
91 PDFNet.Terminate()
92 End Sub
93End Module
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales