PDFDocMemory

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 UWP SDK.

1//
2// Copyright (c) 2001-2020 by PDFTron Systems Inc. All Rights Reserved.
3//
4
5using System;
6using System.IO;
7using System.Threading.Tasks;
8using Windows.Foundation;
9
10using pdftron.PDF;
11using pdftron.SDF;
12
13using PDFNetUniversalSamples.ViewModels;
14
15namespace PDFNetSamples
16{
17 public sealed class PDFDocMemoryTest : Sample
18 {
19 public PDFDocMemoryTest() :
20 base("PDFDocMemory", "The sample illustrates how 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.")
21 {
22 }
23
24 public override IAsyncAction RunAsync()
25 {
26 return Task.Run(new System.Action(async () => {
27 WriteLine("--------------------------------");
28 WriteLine("Starting PDFDocMemory Test...");
29 WriteLine("--------------------------------\n");
30 try
31 {
32 // Read a PDF document from a IRandomAccessStream or pass-in a memory buffer...
33 PDFDoc doc = new PDFDoc(Path.Combine(InputPath, "tiger.pdf"));
34 doc.InitSecurityHandler();
35
36 int num_pages = doc.GetPageCount();
37
38 ElementWriter writer = new ElementWriter();
39 ElementReader reader = new ElementReader();
40 Element element;
41
42 // Perform some document editing ...
43 // Here we simply copy all elements from one page to another.
44 for(int i = 1; i <= num_pages; ++i)
45 {
46 pdftron.PDF.Page pg = doc.GetPage(2 * i - 1);
47
48 reader.Begin(pg);
49 pdftron.PDF.Page new_page = doc.PageCreate(pg.GetMediaBox());
50 doc.PageInsert(doc.GetPageIterator(2*i), new_page);
51
52 writer.Begin(new_page);
53 while ((element = reader.Next()) != null) // Read page contents
54 {
55 writer.WriteElement(element);
56 }
57
58 writer.End();
59 reader.End();
60 }
61
62 string output_file_path = Path.Combine(OutputPath, "doc_memory_edit.pdf");
63 await doc.SaveAsync(output_file_path, SDFDocSaveOptions.e_remove_unused);
64 WriteLine("Done. Results saved in " + output_file_path);
65 await AddFileToOutputList(output_file_path).ConfigureAwait(false);
66
67 // Read some data from the file stored in memory
68 reader.Begin(doc.GetPage(1));
69 while ((element = reader.Next()) != null) {
70 if (element.GetType() == ElementType.e_path)
71 WriteLine("Path, ");
72 }
73 reader.End();
74 doc.Destroy();
75 }
76 catch (Exception e)
77 {
78 WriteLine(GetExceptionMessage(e));
79 }
80
81 WriteLine("\n--------------------------------");
82 WriteLine("Done PDFDocMemory Test.");
83 WriteLine("--------------------------------\n");
84 })).AsAsyncAction();
85 }
86 }
87}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales