Merging pdf files in one line
February 2, 2015

merging pdf files

Merging pdf files into a single one


Merging pdf files has never been so simple using Ghostscript from command line in both Linux and OsX. Just open a console and type:


gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=<yourfile.pdf> <your_list_of_pdfs>

This command will merge pdf files your_list_of_pdfs into a single file called yourfile.pdf.

So easy, that I thought it could have been

worth using it in a Ruby on Rails project.

In the past I used Prawnpdf to create and combine pdfs ,but templates support was dropped in version 0.13.0, disable by default in 0.14.0 and extracted in 0.15.0. Because this was the feature I used for merging pdf files, I had to find a new way to do my stuff and using ghostscript was the simplest choice.

Basically the main idea behnd the following snippet was putting all the file paths in an array and pass them to the above command, right after a join to get a string out of the array was done. In the end what I did was:

Rails snippet to merge an array of pdfs

pdf_paths = my_array_of_files # pdf array of file paths
filename = my_path_to_saving_place # the path to my folder
if pdf_paths.count >0
   # using backtick execute the command
   `gs -sPAPERSIZE=a4 -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=#{filename} #{pdf_paths.join(" ")}` 

To check if ghostscript is installed on your machine type this in your console:

man gs

If it displays the manual entry of Ghostscript you can start using it, otherwise it has to be installed in the following way:

Mac users

brew install ghostscript

Linux users

sudo apt-get update
sudo apt-get install ghostscript

And that’s all!




Slackware how to on merging pdf files

Making system calls with ruby on stackoverflow

Leave a Reply

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.