Cutting and merging PDF files from the command line

piczmar_0

Marcin Piczkowski

Posted on July 21, 2020

Cutting and merging PDF files from the command line


Photo by Sharon McCutcheon on Unsplash

I wanted to show you a few simple commands which saved me a lot of time while tidying up some PDF files.
You can cut them into pages, merge or split based on the page range. Here it is:

  • cut off the first page from input.pdf file and save result as output.pdf
pdftk input.pdf cat 2-end output output.pdf
Enter fullscreen mode Exit fullscreen mode
  • merge file1.pdf and file2.pdf into single output.pdf
gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite \
-sOutputFile=output.pdf file1.pdf file2.pdf 
Enter fullscreen mode Exit fullscreen mode
  • split input.pdf into single-page pdf files starting from 2-nd and ending on 15-th page. It will create files: output_2.pdf, output_3.pdf, output_4.pdf and so on.. up to output_15.pdf
pdfseparate -f 2 -l 15 input.pdf out_%d.pdf
Enter fullscreen mode Exit fullscreen mode
  • convert image to pdf file

First, install img2pdf:

sudo apt-get install img2pdf
Enter fullscreen mode Exit fullscreen mode

Then convert image.jpg to output.pdf:

img2pdf image.jpg -o output.pdf
Enter fullscreen mode Exit fullscreen mode
  • convert multiple images to pdf file

You can do it with another very useful tool - ImageMagic.

You can install it like that:

sudo apt update 
sudo apt-get install build-essential
Enter fullscreen mode Exit fullscreen mode

Then let's say we want to create a pdf file from image1.jpg, image2.jpg and image3.bmp :

convert image1.jpg image2.png image3.bmp -quality 100 output.pdf
Enter fullscreen mode Exit fullscreen mode

You may get error message like:

convert-im6.q16: no images defined `output.pdf' @ error/convert.c/ConvertImageCommand/3258.
Enter fullscreen mode Exit fullscreen mode

This means ImageMagic protects you from processing pdf files. To allow it you need to have root privilege and edit /etc/ImageMagick-6/policy.xml and comment out this line

 <!--policy domain="coder" rights="none" pattern="PDF" --/>
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
piczmar_0
Marcin Piczkowski

Posted on July 21, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related