Convert to PDF to PNG, JPG, BMP or TIFF - Ruby Sample Code

Sample code to use Apryse SDK's built-in rasterizer to render PDF images on the fly and save the resulting images in various raster image formats (such as PNG, JPEG, BMP, TIFF). Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. Learn more about our Server SDK and PDF Conversion Library.

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# Relative path to the folder containing test files.
13input_path = "../../TestFiles/"
14output_path = "../../TestFiles/Output/"
15
16#---------------------------------------------------------------------------------------
17# The following sample illustrates how to convert PDF documents to various raster image
18# formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to
19# GDI+ Bitmap for further manipulation and/or display in WinForms applications.
20#---------------------------------------------------------------------------------------
21
22 # The first step in every application using PDFNet is to initialize the
23 # library and set the path to common PDF resources. The library is usually
24 # initialized only once, but calling Initialize multiple times is also fine.
25 PDFNet.Initialize(PDFTronLicense.Key)
26
27 # Optional: Set ICC color profiles to fine tune color conversion
28 # for PDF 'device' color spaces...
29
30 # PDFNet.SetResourcesPath("../../../resources")
31 # PDFNet.SetColorManagement
32 # PDFNet.SetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc")
33 # PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc") # will search in PDFNet resource folder.
34
35 # ----------------------------------------------------
36 # Optional: Set predefined font mappings to override default font
37 # substitution for documents with missing fonts...
38
39 # PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf")
40 # PDFNet.AddFontSubst("StoneSans", "comic.ttf") # search for 'comic.ttf' in PDFNet resource folder.
41 # PDFNet.AddFontSubst(PDFNet.E_Identity, "C:/WINDOWS/Fonts/arialuni.ttf")
42 # PDFNet.AddFontSubst(PDFNet.E_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf")
43 # PDFNet.AddFontSubst(PDFNet.E_Japan2, "c:/myfonts/KozMinProVI-Regular.otf")
44 # PDFNet.AddFontSubst(PDFNet.E_Korea1, "AdobeMyungjoStd-Medium.otf")
45 # PDFNet.AddFontSubst(PDFNet.E_CNS1, "AdobeSongStd-Light.otf")
46 # PDFNet.AddFontSubst(PDFNet.E_GB1, "AdobeMingStd-Light.otf")
47
48 #Example 1) Convert the first page to PNG and TIFF at 92 DPI.
49
50 # PDFDraw class is used to rasterize PDF pages.
51 draw = PDFDraw.new
52
53 #--------------------------------------------------------------------------------
54 # Example 1) Convert the first page to PNG and TIFF at 92 DPI.
55 # A three step tutorial to convert PDF page to an image.
56
57 # A) Open the PDF document.
58 doc = PDFDoc.new(input_path + "tiger.pdf")
59
60 # Initialize the security handler, in case the PDF is encrypted.
61 doc.InitSecurityHandler
62
63 # B) The output resolution is set to 92 DPI.
64 draw.SetDPI(92)
65
66 # C) Rasterize the first page in the document and save the result as PNG.
67 itr = doc.GetPageIterator
68 draw.Export(itr.Current, output_path + "tiger_92dpi.png")
69
70 puts "Example 1: tiger_92dpi.png"
71
72 # Export the same page as TIFF
73 itr = doc.GetPageIterator
74 draw.Export(itr.Current, (output_path + "tiger_92dpi.tif"), "TIFF")
75
76 #--------------------------------------------------------------------------------
77 # Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
78
79 puts "Example 2:"
80
81 hint_set = ObjSet.new # A collection of rendering 'hits'.
82
83 doc = PDFDoc.new(input_path + "newsletter.pdf")
84 # Initialize the security handler, in case the PDF is encrypted.
85 doc.InitSecurityHandler
86
87 # Set the output resolution is to 72 DPI.
88 draw.SetDPI(72)
89
90 # Use optional encoder parameter to specify JPEG quality.
91 encoder_param = hint_set.CreateDict
92 encoder_param.PutNumber("Quality", 80)
93
94 # Traverse all pages in the document.
95 itr = doc.GetPageIterator
96 while itr.HasNext do
97 filename = "newsletter" + itr.Current.GetIndex.to_s + ".jpg"
98 puts filename
99 draw.Export(itr.Current, output_path + filename, "JPEG", encoder_param)
100 itr.Next
101 end
102 puts "Done."
103
104 # Examples 3-5
105 # Common code for remaining samples.
106 tiger_doc = PDFDoc.new(input_path + "tiger.pdf")
107 # Initialize the security handler, in case the PDF is encrypted.
108 tiger_doc.InitSecurityHandler
109 page = tiger_doc.GetPage(1)
110
111 #--------------------------------------------------------------------------------
112 # Example 3) Convert the first page to raw bitmap. Also, rotate the
113 # page 90 degrees and save the result as RAW.
114 draw.SetDPI(100) # Set the output resolution is to 100 DPI.
115 draw.SetRotate(Page::E_90) # Rotate all pages 90 degrees clockwise.
116 bmp = draw.GetBitmap(page, PDFDraw::E_rgb)
117
118 # Save the raw RGB data to disk.
119 File.open(output_path + "tiger_100dpi_rot90.raw", 'w') { |file| file.write(bmp.GetBuffer) }
120
121 puts "Example 3: tiger_100dpi_rot90.raw"
122
123 draw.SetRotate(Page::E_0) # Disable image rotation for remaining samples.
124
125 #--------------------------------------------------------------------------------
126 # Example 4) Convert PDF page to a fixed image size. Also illustrates some
127 # other features in PDFDraw class such as rotation, image stretching, exporting
128 # to grayscale, or monochrome.
129
130 # Initialize render 'gray_hint' parameter, that is used to control the
131 # rendering process. In this case we tell the rasterizer to export the image as
132 # 1 Bit Per Component (BPC) image.
133 mono_hint = hint_set.CreateDict
134 mono_hint.PutNumber("BPC", 1)
135
136 # SetImageSize can be used instead of SetDPI to adjust page scaling
137 # dynamically so that given image fits into a buffer of given dimensions.
138 draw.SetImageSize(1000, 1000) # Set the output image to be 1000 wide and 1000 pixels tall
139 draw.Export(page, output_path + "tiger_1000x1000.png", "PNG", mono_hint)
140 puts "Example 4: tiger_1000x1000.png"
141
142 draw.SetImageSize(200, 400) # Set the output image to be 200 wide and 400 pixels tall
143 draw.SetRotate(Page::E_180) # Rotate all pages 90 degrees clockwise
144
145 # 'gray_hint' tells the rasterizer to export the image as grayscale.
146 gray_hint = hint_set.CreateDict
147 gray_hint.PutName("ColorSpace", "Gray")
148
149 draw.Export(page, (output_path + "tiger_200x400_rot180.png"), "PNG", gray_hint)
150 puts "Example 4: tiger_200x400_rot180.png"
151
152 draw.SetImageSize(400, 200, false) # The third parameter sets 'preserve-aspect-ratio' to false
153 draw.SetRotate(Page::E_0) # Disable image rotation
154 draw.Export(page, output_path + "tiger_400x200_stretch.jpg", "JPEG")
155 puts "Example 4: tiger_400x200_stretch.jpg"
156
157 #--------------------------------------------------------------------------------
158 # Example 5) Zoom into a specific region of the page and rasterize the
159 # area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
160 zoom_rect = Rect.new(216, 522, 330, 600)
161 page.SetCropBox(zoom_rect) # Set the page crop box.
162
163 # Select the crop region to be used for drawing.
164 draw.SetPageBox(Page::E_crop)
165 draw.SetDPI(900) # Set the output image resolution to 900 DPI.
166 draw.Export(page, output_path + "tiger_zoom_900dpi.png", "PNG")
167 puts "Example 5: tiger_zoom_900dpi.png"
168
169 # -------------------------------------------------------------------------------
170 # Example 6)
171 draw.SetImageSize(50, 50) # Set the thumbnail to be 50x50 pixel image.
172 draw.Export(page, output_path + "tiger_zoom_50x50.png", "PNG")
173 puts "Example 6: tiger_zoom_50x50.png"
174
175 cmyk_hint = hint_set.CreateDict
176 cmyk_hint.PutName("ColorSpace", "CMYK")
177
178 #--------------------------------------------------------------------------------
179 # Example 6) Convert the first PDF page to CMYK TIFF at 92 DPI.
180 # A three step tutorial to convert PDF page to an image
181 # A) Open the PDF document
182 doc = PDFDoc.new(input_path + "tiger.pdf")
183 # Initialize the security handler, in case the PDF is encrypted.
184 doc.InitSecurityHandler
185
186 # The output resolution is set to 92 DPI.
187 draw.SetDPI(92)
188
189 # C) Rasterize the first page in the document and save the result as TIFF.
190 pg = doc.GetPage(1)
191 draw.Export(pg, output_path + "out1.tif", "TIFF", cmyk_hint)
192 puts "Example 7: out1.tif"
193
194 doc.Close
195
196 # A) Open the PDF document.
197 doc = PDFDoc.new(input_path + "tiger.pdf")
198 # Initialize the security handler, in case the PDF is encrypted.
199 doc.InitSecurityHandler
200
201 # B) Get the page matrix
202 pg = doc.GetPage(1)
203 box = Page::E_crop
204 mtx = pg.GetDefaultMatrix(true, box)
205 # We want to render a quadrant, so use half of width and height
206 pg_w = pg.GetPageWidth(box) / 2
207 pg_h = pg.GetPageHeight(box) / 2
208
209 # C) Scale matrix from PDF space to buffer space
210 dpi = 96.0
211 scale = dpi / 72.0 # PDF space is 72 dpi
212 buf_w = ((scale * pg_w).floor).to_i
213 buf_h = ((scale * pg_h).floor).to_i
214 bytes_per_pixel = 4 # BGRA buffer
215 buf_size = buf_w * buf_h * bytes_per_pixel
216 mtx.Translate(0, -pg_h) # translate by '-pg_h' since we want south-west quadrant
217 mtx = Matrix2D.new(scale, 0, 0, scale, 0, 0).Multiply(mtx)
218
219 # D) Rasterize page into memory buffer, according to our parameters
220 rast = PDFRasterizer.new
221 buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx)
222
223 # buf now contains raw BGRA bitmap.
224 puts "Example 8: Successfully rasterized into memory buffer."
225
226 #--------------------------------------------------------------------------------
227 # Example 9) Export raster content to PNG using different image smoothing settings.
228 text_doc = PDFDoc.new(input_path + "lorem_ipsum.pdf")
229 text_doc.InitSecurityHandler
230
231 draw.SetImageSmoothing(false, false)
232 filename = "raster_text_no_smoothing.png"
233 draw.Export(text_doc.GetPageIterator.Current, output_path + filename)
234 puts "Example 9 a): " + filename + ". Done."
235
236 filename = "raster_text_smoothed.png"
237 # default quality bilinear resampling
238 draw.SetImageSmoothing(true, false)
239 draw.Export(text_doc.GetPageIterator.Current, output_path + filename)
240 puts "Example 9 b): " + filename + ". Done."
241
242 filename = "raster_text_high_quality.png"
243 # high quality area resampling
244 draw.SetImageSmoothing(true, true)
245 draw.Export(text_doc.GetPageIterator.Current, output_path + filename)
246 puts "Example 9 c): " + filename + ". Done."
247
248 #--------------------------------------------------------------------------------
249 # Example 10) Export separations directly, without conversion to an output colorspace
250
251 separation_doc = PDFDoc.new(input_path + "op_blend_test.pdf")
252 separation_doc.InitSecurityHandler
253 separation_hint = hint_set.CreateDict
254 separation_hint.PutName("ColorSpace", "Separation")
255 draw.SetDPI(96)
256 draw.SetImageSmoothing(true, true)
257 draw.SetOverprint(PDFRasterizer::E_op_on)
258
259 filename = "merged_separations.png"
260 draw.Export(separation_doc.GetPageIterator.Current, output_path + filename, "PNG")
261 puts "Example 10 a): " + filename + ". Done."
262
263 filename = "separation"
264 draw.Export(separation_doc.GetPageIterator.Current, output_path + filename, "PNG", separation_hint)
265 puts "Example 10 b): " + filename + "_[ink].png. Done."
266
267 filename = "separation_NChannel.tif"
268 draw.Export(separation_doc.GetPageIterator.Current, output_path + filename, "TIFF", separation_hint)
269 puts "Example 10 c): " + filename + ". Done."
270 PDFNet.Terminate

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales