DEV Community

Marcin Piczkowski
Marcin Piczkowski

Posted on • Updated on

 

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

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.