combine_pdf 0.1.23 → 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,141 @@
1
+ # -*- encoding : utf-8 -*-
2
+ ########################################################
3
+ ## Thoughts from reading the ISO 32000-1:2008
4
+ ## this file is part of the CombinePDF library and the code
5
+ ## is subject to the same license.
6
+ ########################################################
7
+
8
+
9
+
10
+
11
+
12
+
13
+ module CombinePDF
14
+
15
+
16
+ class PDF
17
+
18
+ protected
19
+
20
+ include Renderer
21
+
22
+ # @private
23
+ # Some PDF objects contain references to other PDF objects.
24
+ #
25
+ # this function adds the references contained in "object", but DOESN'T add the object itself.
26
+ #
27
+ # this is used for internal operations, such as injectng data using the << operator.
28
+ def add_referenced(object)
29
+ # add references but not root
30
+ case
31
+ when object.is_a?(Array)
32
+ object.each {|it| add_referenced(it)}
33
+ return true
34
+ when object.is_a?(Hash)
35
+ # first if statement is actually a workaround for a bug in Acrobat Reader, regarding duplicate pages.
36
+ if object[:is_reference_only] && object[:referenced_object] && object[:referenced_object].is_a?(Hash) && object[:referenced_object][:Type] == :Page
37
+ if @objects.find_index object[:referenced_object]
38
+ @objects << object[:referenced_object].dup
39
+ else
40
+ @objects << object[:referenced_object]
41
+ end
42
+ elsif object[:is_reference_only] && object[:referenced_object]
43
+ found_at = @objects.find_index object[:referenced_object]
44
+ if found_at
45
+ #if the objects are equal, they might still be different objects!
46
+ # so, we need to make sure they are the same object for the pointers to effect id numbering
47
+ # and formatting operations.
48
+ object[:referenced_object] = @objects[found_at]
49
+ # stop this path, there is no need to run over the Hash's keys and values
50
+ return true
51
+ else
52
+ # @objects.include? object[:referenced_object] is bound to be false
53
+ # the object wasn't found - add it to the @objects array
54
+ @objects << object[:referenced_object]
55
+ end
56
+
57
+ end
58
+ object.each do |k, v|
59
+ add_referenced(v) unless k == :Parent
60
+ end
61
+ else
62
+ return false
63
+ end
64
+ true
65
+ end
66
+
67
+ # @private
68
+ def rebuild_catalog(*with_pages)
69
+ # # build page list v.1 Slow but WORKS
70
+ # # Benchmark testing value: 26.708394
71
+ # old_catalogs = @objects.select {|obj| obj.is_a?(Hash) && obj[:Type] == :Catalog}
72
+ # old_catalogs ||= []
73
+ # page_list = []
74
+ # PDFOperations._each_object(old_catalogs,false) { |p| page_list << p if p.is_a?(Hash) && p[:Type] == :Page }
75
+
76
+ # build page list v.2 faster, better, and works
77
+ # Benchmark testing value: 0.215114
78
+ page_list = pages
79
+
80
+ # add pages to catalog, if requested
81
+ page_list.push(*with_pages) unless with_pages.empty?
82
+
83
+ # build new Pages object
84
+ pages_object = {Type: :Pages, Count: page_list.length, Kids: page_list.map {|p| {referenced_object: p, is_reference_only: true} } }
85
+
86
+ # build new Catalog object
87
+ catalog_object = {Type: :Catalog, Pages: {referenced_object: pages_object, is_reference_only: true} }
88
+ catalog_object[:ViewerPreferences] = @viewer_preferences unless @viewer_preferences.empty?
89
+
90
+ # point old Pages pointers to new Pages object
91
+ ## first point known pages objects - enough?
92
+ pages.each {|p| p[:Parent] = { referenced_object: pages_object, is_reference_only: true} }
93
+ ## or should we, go over structure? (fails)
94
+ # each_object {|obj| obj[:Parent][:referenced_object] = pages_object if obj.is_a?(Hash) && obj[:Parent].is_a?(Hash) && obj[:Parent][:referenced_object] && obj[:Parent][:referenced_object][:Type] == :Pages}
95
+
96
+ # remove old catalog and pages objects
97
+ @objects.reject! {|obj| obj.is_a?(Hash) && (obj[:Type] == :Catalog || obj[:Type] == :Pages) }
98
+
99
+ # inject new catalog and pages objects
100
+ @objects << pages_object
101
+ @objects << catalog_object
102
+
103
+ catalog_object
104
+ end
105
+
106
+ # @private
107
+ # this is an alternative to the rebuild_catalog catalog method
108
+ # this method is used by the to_pdf method, for streamlining the PDF output.
109
+ # there is no point is calling the method before preparing the output.
110
+ def rebuild_catalog_and_objects
111
+ catalog = rebuild_catalog
112
+ @objects = []
113
+ @objects << catalog
114
+ add_referenced catalog
115
+ catalog
116
+ end
117
+
118
+ def get_existing_catalogs
119
+ (@objects.select {|obj| obj.is_a?(Hash) && obj[:Type] == :Catalog}) || (@objects.select {|obj| obj.is_a?(Hash) && obj[:Type] == :Page})
120
+ end
121
+
122
+
123
+
124
+ # end
125
+ # @private
126
+ def renumber_object_ids(start = nil)
127
+ @set_start_id = start || @set_start_id
128
+ start = @set_start_id
129
+ history = {}
130
+ @objects.each do |obj|
131
+ obj[:indirect_reference_id] = start
132
+ start += 1
133
+ end
134
+ end
135
+ def remove_old_ids
136
+ @objects.each {|obj| obj.delete(:indirect_reference_id); obj.delete(:indirect_generation_number)}
137
+ end
138
+
139
+ end
140
+ end
141
+
@@ -0,0 +1,402 @@
1
+ # -*- encoding : utf-8 -*-
2
+ ########################################################
3
+ ## Thoughts from reading the ISO 32000-1:2008
4
+ ## this file is part of the CombinePDF library and the code
5
+ ## is subject to the same license.
6
+ ########################################################
7
+
8
+
9
+
10
+
11
+
12
+
13
+ module CombinePDF
14
+
15
+ # PDF class is the PDF object that can save itself to
16
+ # a file and that can be used as a container for a full
17
+ # PDF file data, including version, information etc'.
18
+ #
19
+ # PDF objects can be used to combine or to inject data.
20
+ # == Combine/Merge PDF files or Pages
21
+ # To combine PDF files (or data):
22
+ # pdf = CombinePDF.new
23
+ # pdf << CombinePDF.load("file1.pdf") # one way to combine, very fast.
24
+ # pdf << CombinePDF.load("file2.pdf")
25
+ # pdf.save "combined.pdf"
26
+ # or even a one liner:
27
+ # (CombinePDF.load("file1.pdf") << CombinePDF.load("file2.pdf") << CombinePDF.load("file3.pdf")).save("combined.pdf")
28
+ # you can also add just odd or even pages:
29
+ # pdf = CombinePDF.new
30
+ # i = 0
31
+ # CombinePDF.load("file.pdf").pages.each do |page|
32
+ # i += 1
33
+ # pdf << page if i.even?
34
+ # end
35
+ # pdf.save "even_pages.pdf"
36
+ # notice that adding all the pages one by one is slower then adding the whole file.
37
+ # == Add content to existing pages (Stamp / Watermark)
38
+ # To add content to existing PDF pages, first import the new content from an existing PDF file.
39
+ # after that, add the content to each of the pages in your existing PDF.
40
+ #
41
+ # in this example, we will add a company logo to each page:
42
+ # company_logo = CombinePDF.load("company_logo.pdf").pages[0]
43
+ # pdf = CombinePDF.load "content_file.pdf"
44
+ # pdf.pages.each {|page| page << company_logo} # notice the << operator is on a page and not a PDF object.
45
+ # pdf.save "content_with_logo.pdf"
46
+ # Notice the << operator is on a page and not a PDF object. The << operator acts differently on PDF objects and on Pages.
47
+ #
48
+ # The << operator defaults to secure injection by renaming references to avoid conflics. For overlaying pages using compressed data that might not be editable (due to limited filter support), you can use:
49
+ # pdf.pages(nil, false).each {|page| page << stamp_page}
50
+ #
51
+ # == Page Numbering
52
+ # adding page numbers to a PDF object or file is as simple as can be:
53
+ # pdf = CombinePDF.load "file_to_number.pdf"
54
+ # pdf.number_pages
55
+ # pdf.save "file_with_numbering.pdf"
56
+ #
57
+ # numbering can be done with many different options, with different formating, with or without a box object, and even with opacity values.
58
+ #
59
+ # == Loading PDF data
60
+ # Loading PDF data can be done from file system or directly from the memory.
61
+ #
62
+ # Loading data from a file is easy:
63
+ # pdf = CombinePDF.load("file.pdf")
64
+ # you can also parse PDF files from memory:
65
+ # pdf_data = IO.read 'file.pdf' # for this demo, load a file to memory
66
+ # pdf = CombinePDF.parse(pdf_data)
67
+ # Loading from the memory is especially effective for importing PDF data recieved through the internet or from a different authoring library such as Prawn.
68
+ class PDF
69
+
70
+ # lists the Hash keys used for PDF objects
71
+ #
72
+ # the CombinePDF library doesn't use special classes for its objects (PDFPage class, PDFStream class or anything like that).
73
+ #
74
+ # there is only one PDF class which represents the whole of the PDF file.
75
+ #
76
+ # this Hash lists the private Hash keys that the CombinePDF library uses to
77
+ # differentiate between complex PDF objects.
78
+ PRIVATE_HASH_KEYS = [:indirect_reference_id, :indirect_generation_number, :raw_stream_content, :is_reference_only, :referenced_object, :indirect_without_dictionary]
79
+
80
+ # the objects attribute is an Array containing all the PDF sub-objects for te class.
81
+ attr_reader :objects
82
+ # the info attribute is a Hash that sets the Info data for the PDF.
83
+ # use, for example:
84
+ # pdf.info[:Title] = "title"
85
+ attr_reader :info
86
+ # set/get the PDF version of the file (1.1-1.7) - shuold be type Float.
87
+ attr_accessor :version
88
+ # the viewer_preferences attribute is a Hash that sets the ViewerPreferences data for the PDF.
89
+ # use, for example:
90
+ # pdf.viewer_preferences[:HideMenubar] = true
91
+ attr_reader :viewer_preferences
92
+
93
+ def initialize (parser = nil)
94
+ # default before setting
95
+ @objects = []
96
+ @version = 0
97
+ @viewer_preferences, @info = {}, {}
98
+ parser ||= PDFParser.new("")
99
+ raise TypeError, "initialization error, expecting CombinePDF::PDFParser or nil, but got #{parser.class.name}" unless parser.is_a? PDFParser
100
+ @objects = parser.parse
101
+ # remove any existing id's
102
+ remove_old_ids
103
+ # set data from parser
104
+ @version = parser.version if parser.version.is_a? Float
105
+ @info = parser.info_object || {}
106
+
107
+ # general globals
108
+ @set_start_id = 1
109
+ @info[:Producer] = "Ruby CombinePDF #{CombinePDF::VERSION} Library by B. Segev"
110
+ @info.delete :CreationDate
111
+ @info.delete :ModDate
112
+ end
113
+
114
+ # adds a new page to the end of the PDF object.
115
+ #
116
+ # returns the new page object.
117
+ def new_page(mediabox = [0, 0, 595.3, 841.9], location = -1)
118
+ p = PDFWriter.new(mediabox)
119
+ insert(-1, p )
120
+ p
121
+ end
122
+
123
+ # get the title for the pdf
124
+ # The title is stored in the information dictionary and isn't required
125
+ def title
126
+ return @info[:Title]
127
+ end
128
+ # set the title for the pdf
129
+ # The title is stored in the information dictionary and isn't required
130
+ # new_title:: a string that is the new author value.
131
+ def title=(new_title = nil)
132
+ @info[:Title] = new_title
133
+ end
134
+ # get the author value for the pdf.
135
+ # The author is stored in the information dictionary and isn't required
136
+ def author
137
+ return @info[:Author]
138
+ end
139
+ # set the author value for the pdf.
140
+ # The author is stored in the information dictionary and isn't required
141
+ #
142
+ # new_title:: a string that is the new author value.
143
+ def author=(new_author = nil)
144
+ @info[:Author] = new_author
145
+ end
146
+
147
+ # Save the PDF to file.
148
+ #
149
+ # file_name:: is a string or path object for the output.
150
+ #
151
+ # **Notice!** if the file exists, it **WILL** be overwritten.
152
+ def save(file_name)
153
+ IO.binwrite file_name, to_pdf
154
+ end
155
+
156
+ # Formats the data to PDF formats and returns a binary string that represents the PDF file content.
157
+ #
158
+ # This method is used by the save(file_name) method to save the content to a file.
159
+ #
160
+ # use this to export the PDF file without saving to disk (such as sending through HTTP ect').
161
+ def to_pdf
162
+ #reset version if not specified
163
+ @version = 1.5 if @version.to_f == 0.0
164
+ #set creation date for merged file
165
+ @info[:CreationDate] = Time.now.strftime "D:%Y%m%d%H%M%S%:::z'00"
166
+ #rebuild_catalog
167
+ catalog = rebuild_catalog_and_objects
168
+ # add ID and generation numbers to objects
169
+ renumber_object_ids
170
+
171
+ out = []
172
+ xref = []
173
+ indirect_object_count = 1 #the first object is the null object
174
+ #write head (version and binanry-code)
175
+ out << "%PDF-#{@version.to_s}\n%\xFF\xFF\xFF\xFF\xFF\x00\x00\x00\x00".force_encoding(Encoding::ASCII_8BIT)
176
+
177
+ #collect objects and set xref table locations
178
+ loc = 0
179
+ out.each {|line| loc += line.bytesize + 1}
180
+ @objects.each do |o|
181
+ indirect_object_count += 1
182
+ xref << loc
183
+ out << object_to_pdf(o)
184
+ loc += out.last.bytesize + 1
185
+ end
186
+ xref_location = loc
187
+ # xref_location = 0
188
+ # out.each { |line| xref_location += line.bytesize + 1}
189
+ out << "xref\n0 #{(indirect_object_count).to_s}\n0000000000 65535 f \n"
190
+ xref.each {|offset| out << ( out.pop + ("%010d 00000 n \n" % offset) ) }
191
+ out << out.pop + "trailer"
192
+ out << "<<\n/Root #{false || "#{catalog[:indirect_reference_id]} #{catalog[:indirect_generation_number]} R"}"
193
+ out << "/Size #{indirect_object_count.to_s}"
194
+ if @info.is_a?(Hash)
195
+ PRIVATE_HASH_KEYS.each {|key| @info.delete key} # make sure the dictionary is rendered inline, without stream
196
+ out << "/Info #{object_to_pdf @info}"
197
+ end
198
+ out << ">>\nstartxref\n#{xref_location.to_s}\n%%EOF"
199
+ # when finished, remove the numbering system and keep only pointers
200
+ remove_old_ids
201
+ # output the pdf stream
202
+ out.join("\n").force_encoding(Encoding::ASCII_8BIT)
203
+ end
204
+
205
+ # this method returns all the pages cataloged in the catalog.
206
+ #
207
+ # if no catalog is passed, it seeks the existing catalog(s) and searches
208
+ # for any registered Page objects.
209
+ #
210
+ # Page objects are Hash class objects. the page methods are added using a mixin or inheritance.
211
+ #
212
+ # catalogs:: a catalog, or an Array of catalog objects. defaults to the existing catalog.
213
+ def pages(catalogs = nil)
214
+ page_list = []
215
+ catalogs ||= get_existing_catalogs
216
+
217
+ if catalogs.is_a?(Array)
218
+ catalogs.each {|c| page_list.push *( pages(c) ) unless c.nil?}
219
+ elsif catalogs.is_a?(Hash)
220
+ if catalogs[:is_reference_only]
221
+ if catalogs[:referenced_object]
222
+ page_list.push *( pages(catalogs[:referenced_object]) )
223
+ else
224
+ warn "couldn't follow reference!!! #{catalogs} not found!"
225
+ end
226
+ else
227
+ case catalogs[:Type]
228
+ when :Page
229
+ page_list << catalogs
230
+ when :Pages
231
+ page_list.push *(pages(catalogs[:Kids])) unless catalogs[:Kids].nil?
232
+ when :Catalog
233
+ page_list.push *(pages(catalogs[:Pages])) unless catalogs[:Pages].nil?
234
+ end
235
+ end
236
+ end
237
+ page_list
238
+ end
239
+
240
+ # returns an array with the different fonts used in the file.
241
+ #
242
+ # Type0 font objects ( "font[:Subtype] == :Type0" ) can be registered with the font library
243
+ # for use in PDFWriter objects (font numbering / table creation etc').
244
+ # @param limit_to_type0 [true,false] limits the list to type0 fonts.
245
+ def fonts(limit_to_type0 = false)
246
+ fonts_array = []
247
+ pages.each do |p|
248
+ p[:Resources][:Font].values.each do |f|
249
+ f = f[:referenced_object] if f[:referenced_object]
250
+ if (limit_to_type0 || f[:Subtype] = :Type0) && f[:Type] == :Font && !fonts_array.include?(f)
251
+ fonts_array << f
252
+ end
253
+ end
254
+ end
255
+ fonts_array
256
+ end
257
+
258
+ # add the pages (or file) to the PDF (combine/merge) and RETURNS SELF, for nesting.
259
+ # for example:
260
+ #
261
+ # pdf = CombinePDF.new "first_file.pdf"
262
+ #
263
+ # pdf << CombinePDF.new "second_file.pdf"
264
+ #
265
+ # pdf.save "both_files_merged.pdf"
266
+ # data:: is PDF page (Hash), and Array of PDF pages or a parsed PDF object to be added.
267
+ def << (data)
268
+ insert -1, data
269
+ end
270
+
271
+ # add the pages (or file) to the BEGINNING of the PDF (combine/merge) and RETURNS SELF for nesting operators.
272
+ # for example:
273
+ #
274
+ # pdf = CombinePDF.new "second_file.pdf"
275
+ #
276
+ # pdf >> CombinePDF.new "first_file.pdf"
277
+ #
278
+ # pdf.save "both_files_merged.pdf"
279
+ # data:: is PDF page (Hash), and Array of PDF pages or a parsed PDF object to be added.
280
+ def >> (data)
281
+ insert 0, data
282
+ end
283
+
284
+ # add PDF pages (or PDF files) into a specific location.
285
+ #
286
+ # returns the new pages Array! (unlike `#<<`, doesn't return self!)
287
+ #
288
+ # location:: the location for the added page(s). Could be any number. negative numbers represent a count backwards (-1 being the end of the page array and 0 being the begining). if the location is beyond bounds, the pages will be added to the end of the PDF object (or at the begining, if the out of bounds was a negative number).
289
+ # data:: a PDF page, a PDF file (CombinePDF.new "filname.pdf") or an array of pages (CombinePDF.new("filname.pdf").pages[0..3]).
290
+ def insert(location, data)
291
+ pages_to_add = nil
292
+ if data.is_a? PDF
293
+ @version = [@version, data.version].max
294
+ pages_to_add = data.pages
295
+ elsif data.is_a?(Array) && (data.select {|o| !(o.is_a?(Hash) && o[:Type] == :Page) } ).empty?
296
+ pages_to_add = data
297
+ elsif data.is_a?(Hash) && data[:Type] == :Page
298
+ pages_to_add = [data]
299
+ else
300
+ warn "Shouldn't add objects to the file unless they are PDF objects or PDF pages (an Array or a single PDF page)."
301
+ return false # return false, which will also stop any chaining.
302
+ end
303
+ catalog = rebuild_catalog
304
+ pages_array = catalog[:Pages][:referenced_object][:Kids]
305
+ page_count = pages_array.length
306
+ if location < 0 && (page_count + location < 0 )
307
+ location = 0
308
+ elsif location > 0 && (location > page_count)
309
+ location = page_count
310
+ end
311
+ pages_array.insert location, pages_to_add
312
+ pages_array.flatten!
313
+ self
314
+ end
315
+
316
+ # removes a PDF page from the file and the catalog
317
+ #
318
+ # returns the removed page.
319
+ #
320
+ # returns nil if failed or if out of bounds.
321
+ #
322
+ # page_index:: the page's index in the zero (0) based page array. negative numbers represent a count backwards (-1 being the end of the page array and 0 being the begining).
323
+ def remove(page_index)
324
+ catalog = rebuild_catalog
325
+ pages_array = catalog[:Pages][:referenced_object][:Kids]
326
+ removed_page = pages_array.delete_at page_index
327
+ catalog[:Pages][:referenced_object][:Count] = pages_array.length
328
+ removed_page
329
+ end
330
+
331
+
332
+ # add page numbers to the PDF
333
+ #
334
+ # For unicode text, a unicode font(s) must first be registered. the registered font(s) must supply the
335
+ # subset of characters used in the text. UNICODE IS AN ISSUE WITH THE PDF FORMAT - USE CAUSION.
336
+ #
337
+ # options:: a Hash of options setting the behavior and format of the page numbers:
338
+ # - :number_format a string representing the format for page number. defaults to ' - %s - ' (allows for letter numbering as well, such as "a", "b"...).
339
+ # - :number_location an Array containing the location for the page numbers, can be :top, :buttom, :top_left, :top_right, :bottom_left, :bottom_right. defaults to [:top, :buttom].
340
+ # - :start_at a Fixnum that sets the number for first page number. also accepts a letter ("a") for letter numbering. defaults to 1.
341
+ # - :margin_from_height a number (PDF points) for the top and buttom margins. defaults to 45.
342
+ # - :margin_from_side a number (PDF points) for the left and right margins. defaults to 15.
343
+ # the options Hash can also take all the options for PDFWriter#textbox.
344
+ # defaults to font: :Helvetica, font_size: 12 and no box (:border_width => 0, :box_color => nil).
345
+ def number_pages(options = {})
346
+ opt = {
347
+ number_format: ' - %s - ',
348
+ number_location: [:top, :bottom],
349
+ start_at: 1,
350
+ font_size: 12,
351
+ font: :Helvetica,
352
+ margin_from_height: 45,
353
+ margin_from_side: 15
354
+ }
355
+ opt.update options
356
+ page_number = opt[:start_at]
357
+ pages.each do |page|
358
+ # Get page dimensions
359
+ mediabox = page[:CropBox] || page[:MediaBox] || [0, 0, 595.3, 841.9]
360
+ # set stamp text
361
+ text = opt[:number_format] % page_number
362
+ # compute locations for text boxes
363
+ text_dimantions = page.dimensions_of( text, opt[:font], opt[:font_size] )
364
+ box_width = text_dimantions[0] * 1.2
365
+ box_height = text_dimantions[1] * 2
366
+ opt[:width] = box_width
367
+ opt[:height] = box_height
368
+ from_height = opt[:margin_from_height]
369
+ from_side = opt[:margin_from_side]
370
+ page_width = mediabox[2]
371
+ page_height = mediabox[3]
372
+ center_position = (page_width - box_width)/2
373
+ left_position = from_side
374
+ right_position = page_width - from_side - box_width
375
+ top_position = page_height - from_height
376
+ bottom_position = from_height + box_height
377
+ if opt[:number_location].include? :top
378
+ page.textbox text, {x: center_position, y: top_position }.merge(opt)
379
+ end
380
+ if opt[:number_location].include? :bottom
381
+ page.textbox text, {x: center_position, y: bottom_position }.merge(opt)
382
+ end
383
+ if opt[:number_location].include? :top_left
384
+ page.textbox text, {x: left_position, y: top_position }.merge(opt)
385
+ end
386
+ if opt[:number_location].include? :bottom_left
387
+ page.textbox text, {x: left_position, y: bottom_position }.merge(opt)
388
+ end
389
+ if opt[:number_location].include? :top_right
390
+ page.textbox text, {x: right_position, y: top_position }.merge(opt)
391
+ end
392
+ if opt[:number_location].include? :bottom_right
393
+ page.textbox text, {x: right_position, y: bottom_position }.merge(opt)
394
+ end
395
+ page_number = page_number.succ
396
+ end
397
+ end
398
+
399
+ end
400
+
401
+ end
402
+