Last active
December 11, 2015 07:09
-
-
Save verticonaut/4564433 to your computer and use it in GitHub Desktop.
Merging PDFs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ************************************************************************************************ | |
# *** Mergin with ghostscript | |
# ************************************************************************************************ | |
GhostScript = `which gs`.chomp | |
dir = Rails.root.join('tmp').to_s | |
file_names = [ | |
'2013_01_24_Pfandhalterschaft_DE.pdf', | |
'2013_01_24_Passivitaetserklaerung_DE.pdf', | |
'2013_01_24_Pfandhalterschaft_DE.pdf', | |
] | |
# @return [String] | |
# The binary … | |
def merge_pdfs(files) | |
ro,wo = IO.pipe | |
re,we = IO.pipe | |
spawn(GhostScript, '-dBATCH', '-dNOPAUSE', '-q', '-sDEVICE=pdfwrite', '-sOUTPUTFILE=-', *files, out: wo, err: we) | |
wo.close | |
we.close | |
ro.read | |
end | |
files = file_names.map { |file_name| "#{dir}/#{file_name}" } | |
merged_pdf = merge_pdfs(files) | |
File.open('merged.pdf', 'w') {|f| f.write(merged_pdf) } | |
# ************************************************************************************************ | |
# *** Mwergin with Prawn | |
# ************************************************************************************************ | |
bundle = HappyPackage::Bundle.for(bundle_key) | |
bundle_pdf = Service::Pdf::Merge.new(bundle.file_paths(locale)) | |
bundle_pdf.to_pdf | |
# service ---------------------------------------------------------------------------------------- | |
require 'prawn' | |
# Merges multiple pdfs into one pdf | |
class Service::Pdf::Merge | |
# @param [Array] Absolute paths of the pdfs. For multipage pdf pass an array with pagecount and the path. | |
def initialize(pdfs=[]) | |
@pdfs = pdfs.map {|e| e.is_a?(Array) ? (e if File.file?(e[1])) : ([1, e] if File.file?(e)) }.compact | |
end | |
# Renders the pdfs to one pdf. | |
# | |
# @return [String] PDF | |
def to_pdf | |
raise 'No pdf paths defined' if @pdfs.empty? | |
pdf = Prawn::Document.new template: @pdfs[0][1] | |
current_page = @pdfs[0][0] | |
pdf.go_to_page current_page | |
@pdfs[1..-1].each do |page| | |
pdf.start_new_page template: page[1] | |
current_page += page[0] | |
pdf.go_to_page current_page | |
end if @pdfs.count > 1 | |
pdf.render | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment