Read & Write PDF in Memory Buffer - Ruby Sample Code

Sample code for using Apryse SDK to read/write a PDF document from/to memory buffer; provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. 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-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 ..."

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales