Method: CombinePDF::PDF#to_pdf

Defined in:
lib/combine_pdf/pdf_public.rb

#to_pdf(options = {}) ⇒ Object

Formats the data to PDF formats and returns a binary string that represents the PDF file content.

This method is used by the save(file_name) method to save the content to a file.

use this to export the PDF file without saving to disk (such as sending through HTTP ect’).



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/combine_pdf/pdf_public.rb', line 176

def to_pdf(options = {})
  # reset version if not specified
  @version = 1.5 if @version.to_f == 0.0

  # set info for merged file
  unless(@info[:CreationDate].is_a?(String))
    @info[:CreationDate] = Time.now unless @info[:CreationDate].is_a?(Time)
    @info[:CreationDate] = @info[:CreationDate].getgm.strftime("D:%Y%m%d%H%M%S%:::z'00")
  end
  @info[:Subject] = options[:subject] if options[:subject]
  @info[:Producer] = options[:producer] if options[:producer]
  # rebuild_catalog
  catalog = rebuild_catalog_and_objects
  # add ID and generation numbers to objects
  renumber_object_ids

  out = []
  xref = []
  indirect_object_count = 1 # the first object is the null object
  # write head (version and binanry-code)
  out << "%PDF-#{@version}\n%\xFF\xFF\xFF\xFF\xFF\x00\x00\x00\x00".force_encoding(Encoding::ASCII_8BIT)

  # collect objects and set xref table locations
  loc = 0
  out.each { |line| loc += line.bytesize + 1 }
  @objects.each do |o|
    indirect_object_count += 1
    xref << loc
    out << object_to_pdf(o)
    loc += out.last.bytesize + 1
  end
  xref_location = loc
  # xref_location = 0
  # out.each { |line| xref_location += line.bytesize + 1}
  out << "xref\n0 #{indirect_object_count}\n0000000000 65535 f "
  xref.each { |offset| out << ("%010d 00000 n ".freeze % offset) }
  out << 'trailer'.freeze
  out << "<<\n/Root #{false || "#{catalog[:indirect_reference_id]} #{catalog[:indirect_generation_number]} R"}"
  out << "/Size #{indirect_object_count}"
  out << "/Info #{@info[:indirect_reference_id]} #{@info[:indirect_generation_number]} R"
  out << ">>\nstartxref\n#{xref_location}\n%%EOF"
  # when finished, remove the numbering system and keep only pointers
  remove_old_ids
  # output the pdf stream
  out.join("\n".b).force_encoding(Encoding::ASCII_8BIT)
end