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 Xamarin SDK.
1//
2// Copyright (c) 2001-2021 by PDFTron Systems 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.
16using NUnit.Framework;
17
18namespace MiscellaneousSamples
19{
20 [TestFixture]
21 public class PDFDocMemoryTest
22 {
23
24 [Test]
25 public static void Sample()
26 {
27
28 // Relative path to the folder containing test files.
29 const string input_path = "TestFiles/";
30
31 try
32 {
33 // Read a PDF document from a stream or pass-in a memory buffer...
34 FileStream istm = new FileStream(Utils.GetAssetTempFile(input_path + "tiger.pdf"), FileMode.Open, FileAccess.Read);
35 using (PDFDoc doc = new PDFDoc(istm))
36 using (ElementWriter writer = new ElementWriter())
37 using (ElementReader reader = new ElementReader())
38 {
39 doc.InitSecurityHandler();
40
41 int num_pages = doc.GetPageCount();
42
43 Element element;
44
45 // Perform some document editing ...
46 // Here we simply copy all elements from one page to another.
47 for(int i = 1; i <= num_pages; ++i)
48 {
49 Page pg = doc.GetPage(2 * i - 1);
50
51 reader.Begin(pg);
52 Page new_page = doc.PageCreate(pg.GetMediaBox());
53 doc.PageInsert(doc.GetPageIterator(2*i), new_page);
54
55 writer.Begin(new_page);
56 while ((element = reader.Next()) != null) // Read page contents
57 {
58 writer.WriteElement(element);
59 }
60
61 writer.End();
62 reader.End();
63 }
64
65 doc.Save(Utils.CreateExternalFile("doc_memory_edit.pdf"), SDFDoc.SaveOptions.e_remove_unused);
66
67 // Save the document to a stream or a memory buffer...
68 using (FileStream ostm = new FileStream(Utils.CreateExternalFile("doc_memory_edit.txt"), FileMode.Create, FileAccess.Write)) {
69 doc.Save(ostm, SDFDoc.SaveOptions.e_remove_unused);
70 }
71
72 // Read some data from the file stored in memory
73 reader.Begin(doc.GetPage(1));
74 while ((element = reader.Next()) != null) {
75 if (element.GetType() == Element.Type.e_path)
76 Console.Write("Path, ");
77 }
78 reader.End();
79
80 Console.WriteLine("");
81 Console.WriteLine("");
82 Console.WriteLine("Done. Result saved in doc_memory_edit.pdf and doc_memory_edit.txt ...");
83 }
84 }
85 catch (PDFNetException e)
86 {
87 Console.WriteLine(e.Message);
88 Assert.True(false);
89 }
90 }
91 }
92}
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales