Skip to content

Instantly share code, notes, and snippets.

@josue
Last active December 10, 2023 15:11
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save josue/dc6a60d9a8054f94b7f6 to your computer and use it in GitHub Desktop.
Save josue/dc6a60d9a8054f94b7f6 to your computer and use it in GitHub Desktop.
Using ImageMagick to easily: Split, Merge, Remove a page from PDF.

Install Required libraries:

sudo apt-get update && sudo apt-get install imagemagick gs

create directory to test commands

mkdir -p pdf_conversion/{merged,split}
cd pdf_conversion

download sample multi-page pdf to test with

curl -o LargeSample.pdf "http://cl.ly/0o1T453E153m/download/LargeSample.pdf"

Split a pdf into separate images

convert LargeSample.pdf split/page-%0d.jpg

Merge separate images into one full pdf.

convert split/*.jpg merged/full.pdf

Remove a page from a full pdf.

convert LargeSample.pdf split/page-%0d.jpg
rm split/page-2.jpg
convert split/*.jpg merged/full.pdf

With PHP: You can use PHP exec function to run these commands, ie:

<?php
exec('convert LargeSample.pdf split/page-%0d.jpg');

Links to read:

http://linuxcommando.blogspot.com/2015/03/how-to-merge-or-split-pdf-files-using.html http://linuxcommando.blogspot.com/2013/02/splitting-up-is-easy-for-pdf-file.html http://stackoverflow.com/questions/17025515/converting-a-multi-page-pdf-to-multiple-pages-using-a-single-command http://codetheory.in/convert-split-pdf-files-into-images-with-imagemagick-and-ghostscript/

@josue
Copy link
Author

josue commented Feb 6, 2016

You can test the above via OSX by install with brew:

brew update
brew install imagemagick gs

@crabbly
Copy link

crabbly commented Feb 6, 2016

Awesome!

@haiahems
Copy link

Thanks!

@Newbytee
Copy link

This method to remove pages from a PDF isn't exactly ideal since text loses significant clarify due to that it all becomes one big image instead of separately rendered elements. It's probably useful in some cases, but if you need clear text this won't cut it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment