1507

How could I merge / convert multiple PDF files into one large PDF file?

I tried the following, but the content of the target file was not as expected:

convert file1.pdf file2.pdf merged.pdf

I need a very simple/basic command line (CLI) solution. Best would be if I could pipe the output of the merge / convert straight into pdf2ps ( as originally attempted in my previously asked question here: Linux piping ( convert -> pdf2ps -> lp) ).

8
  • 4
    ymmv, but this doesn't seem to have as good of a resolution in the output file as pdfunite and it also results in a file size larger than the output from pdfunite
    – sabujp
    Nov 17, 2015 at 23:02
  • 1
  • 1
    Whenever links are preserved or not by those solutions is discussed in this post. If you want to preserve the links (probably along with other annotations), use pdftk if want a command-line interface, pdfsam if you want graphical user interface, sejda if you want a web interface.
    – Clément
    Mar 5, 2020 at 3:02
  • 1
    The convert command line is from ImageMagick and it converts the PDF to an image before doing whatever else it will be doing. Dec 23, 2021 at 1:15
  • 2
    pdftk PDF1.pdf PDF2.pdf cat output PDF3.pdf works fine Sep 16, 2022 at 21:14

23 Answers 23

1994

Considering that pdfunite is part of poppler it has a higher chance to be installed, usage is also simpler than pdftk:

⚠ IMPORTANT: Just make sure you remember to provide out.pdf, or else it will overwrite the last input file in your command ⚠

pdfunite in-1.pdf in-2.pdf in-n.pdf out.pdf

A safer solution may include a test of non-existence
targeting the output file

export output_file=out.pdf && \
! test -e $output_file && \
pdfunite in-1.pdf in-2.pdf in-n.pdf $output_file
30
  • 27
    It is fast, but it seems to break hyperlinks. See blog.dbrgn.ch/2013/8/14/merge-multiple-pdfs Aug 14, 2013 at 9:46
  • 569
    Just make sure you remember to provide out.pdf, or else it will overwrite the last file in your command, sigh.
    – mlissner
    Oct 19, 2013 at 22:20
  • 12
    package for pdfunite is poppler-utils in debian but may not be present in old debian releases. Nov 10, 2013 at 12:16
  • 27
    Cannot recommend this. The size of the the resulting PDF is far too big. For example: Pdfunite gives me a 75MB file while Ghostscript packs everything into 1MB.
    – Torben
    Dec 6, 2013 at 11:58
  • 88
    You can use: pdfunite *.pdf out.pdf assuming no other pdf exists in that directory and their order is preserved by "*". If its not preserved, using ranges: filename_{0..9}.pdf solves it.
    – lepe
    Jan 5, 2015 at 5:48
762

Try the good ghostscript:

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=merged.pdf mine1.pdf mine2.pdf

or even this way for an improved version for low resolution PDFs (thanks to Adriano for pointing this out):

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=merged.pdf mine1.pdf mine2.pdf

In both cases the ouput resolution is much higher and better than this way using convert:

convert -density 300x300 -quality 100 mine1.pdf mine2.pdf merged.pdf

In this way you wouldn't need to install anything else, just work with what you already have installed in your system (at least both come by default in my box).

UPDATE #1: first of all thanks for all your nice comments!! just a tip that may work for you guys, after googleing, I found a superb trick to shrink the size of PDFs, I reduced with it one PDF of 300 MB to just 15 MB with an acceptable resolution! and all of this with the good ghostscript, here it is:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/default -dNOPAUSE -dQUIET -dBATCH -dDetectDuplicateImages -dCompressFonts=true -r150 -sOutputFile=output.pdf input.pdf

UPDATE #2: In case you need to "burn" edits and compress a PDF made with Acrobat, this would help:

gs -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -dCompatibilityLevel=1.3 -dPDFSETTINGS=/screen -dEmbedAllFonts=true -dSubsetFonts=true -dColorImageDownsampleType=/Bicubic -dColorImageResolution=144 -dGrayImageDownsampleType=/Bicubic -dGrayImageResolution=144 -dMonoImageDownsampleType=/Bicubic -dMonoImageResolution=144 -sOutputFile=compressed.pdf withedits.pdf
23
  • 35
    Nice tip, gs runs very fast and it compresses a lot. However, the quality improved a lot after I used this param: -dPDFSETTINGS=/prepress
    – Adriano P
    Dec 15, 2013 at 23:39
  • 7
    I found that -dPDFSETTINGS=/prepress has the very nice effect of rotating pages that are too wide and force annoying horizontal scroll bars.
    – r_31415
    Aug 21, 2014 at 3:40
  • 35
    Add the following line to your .bash_profile and you have a nice shortcut: pdfmerge() { gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=$@ ; } This saves you some typing, if you have to use the command a lot. The usage looks like this: pdfmerge merged.pdf mine1.pdf mine2.pdf
    – Torben
    Jul 22, 2015 at 21:36
  • 15
    The gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=merged.pdf mine1.pdf mine2.pdf can be shortened to the gs -q -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -o merged.pdf mine1.pdf mine2.pdf. From Documentation: "As a convenient shorthand you can use the -o option followed by the output file specification as discussed above. The -o option also sets the -dBATCH and -dNOPAUSE options. This is intended to be a quick way to invoke ghostscript to convert one or more input files."
    – MiniMax
    Apr 24, 2019 at 21:35
  • 7
    @Winny I needed to add dPrinted=false to preserve hyperlinks. Otherwise it broke the links for all but the first pdf. See tex.stackexchange.com/questions/245801/…
    – qdread
    Nov 20, 2020 at 2:11
653

I'm sorry, I managed to find the answer myself using google and a bit of luck : )

For those interested;

I installed the pdftk (pdf toolkit) on our debian server, and using the following command I achieved desired output:

pdftk file1.pdf file2.pdf cat output output.pdf

OR

gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf file1.pdf file2.pdf file3.pdf ...

This in turn can be piped directly into pdf2ps.

23
  • 83
    Using ghostscript also might work: gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=out.pdf in1.pdf in2.pdf in3.pdf ...
    – Nate Kohl
    Mar 24, 2010 at 13:08
  • 19
    It is worth to mention that pdftk can merge encrypted pdfs while pdfunite cant
    – Thomas
    Apr 28, 2013 at 18:54
  • 3
    gives better resolution with pdftk compare to convert in default options. Mar 18, 2014 at 9:44
  • 14
    pdftk file1.pdf file2.pdf cat output out.pdf will output the merged file as out.pdf
    – jmiserez
    Sep 28, 2015 at 19:44
  • 2
    pdftk is not available for EL7 systems due to missing dependency libgcj.
    – a coder
    Mar 22, 2016 at 20:03
160

This is the easiest solution if you have multiple files and do not want to type in the names one by one:

qpdf --empty --pages *.pdf -- out.pdf
10
  • 5
    qpdf seems to break hyperlinks in the document
    – David
    Oct 29, 2019 at 12:51
  • 8
    Although difficult to get your head around the complex options to start with, qpdf is a very handy and powerful tool. Online documentation is available here Dec 18, 2019 at 11:33
  • 1
    Came here looking for a qpdf solution but didn't want to wade through the documentation yet again to figure it out, thank you. Jul 15, 2020 at 23:27
  • 1
    Using a shell wildcard is great as long as the order works for you! Check the order first with echo *.pdf | tr ' ' $'\n' or so! Oct 24, 2020 at 10:06
  • 1
    Qpdf is high in quality and actively maintained, which makes it a much better option than pdftk.
    – user1142217
    Jul 1, 2021 at 13:26
57

Also pdfjoin a.pdf b.pdf will create a new b-joined.pdf with the contents of a.pdf and b.pdf

8
  • 7
    This is nice and succinct, but breaks hyperlinks. Oct 20, 2014 at 1:36
  • 3
    pdfjoin (pdflatex) fails with files with lots of pages. Failed to merge to 1k pages files.
    – mdrozdziel
    Dec 9, 2014 at 12:05
  • 1
    pdfjoin breaks annotations or additional non graphics items
    – sabujp
    Mar 8, 2016 at 21:19
  • 10
    pdfunite usually works well, but if it says "Unimplemented Feature: Could not merge encrypted files ", pdfjoin is a nice alternative. For whatever reason, pdfjoin doesn't complain of encryption.
    – Calaf
    Feb 24, 2017 at 5:59
  • 1
    pdfjam package doesn't include pdfjoin script anymore. You can find the script here Jul 15, 2020 at 13:46
52

pdfunite is fine to merge entire PDFs. If you want, for example, pages 2-7 from file1.pdf and pages 1,3,4 from file2.pdf, you have to use pdfseparate to split the files into separate PDFs for each page to give to pdfunite.

At that point you probably want a program with more options. qpdf is the best utility I've found for manipulating PDFs. pdftk is bigger and slower and Red Hat/Fedora don't package it because of its dependency on gcj. Other PDF utilities have Mono or Python dependencies. I found qpdf produced a much smaller output file than using pdfseparate and pdfunite to assemble pages into a 30-page output PDF, 970kB vs. 1,6450 kB. Because it offers many more options, qpdf's command line is not as simple; the original request to merge file1 and file2 can be performed with

qpdf --empty --pages file1.pdf file2.pdf -- merged.pdf
4
  • 3
    So much this. Parabola for instance doesn’t package pdftk anymore either because of its dependance on gcj, for which support has been dropped I believe. Despite searching for pdf manipulation tools via pacman -Ss pdf, I missed this. Thanks for this answer! I should receive way more upvotes, so it shows up right next to suggestions for pdfunite or pdftk.
    – k.stm
    Sep 19, 2018 at 20:39
  • 1
    On my fresh install of Linux Mint, this ran in the Terminal window without requiring any installs or path adjustments. Nice! Jun 14, 2019 at 14:03
  • This worked perfectly and also gave a clearer merged document that the other commands I tried out. Thanks for the post. Mar 29, 2020 at 19:07
  • 1
    If pages in the even.pdf file are reversed (typical when you scan on a non-double-sided scanner), you will want to use this instead: qpdf --collate --empty --pages odd.pdf even.pdf z-1 -- merged.pdf
    – caram
    Feb 13, 2021 at 22:23
38

You can use the convert command directly,

e.g.

convert sub1.pdf sub2.pdf sub3.pdf merged.pdf
5
  • 51
    This is not lossless.
    – Ben Ruijl
    Jun 3, 2014 at 14:47
  • 15
    You can convert -compress lossless sub1.pdf sub2.pdf sub3.pdf merged.pdf, but the resulting file size's could be way too big. I'd suggest convert -compress jpeg -quality 90 sub1.pdf sub2.pdf sub3.pdf merged.pdf instead.
    – arielnmz
    Aug 5, 2014 at 19:53
  • 27
    This involves converting everything to raster images, it seems, which is definitely not the best, especially when dealing with text-based PDFs. Aug 28, 2014 at 18:38
  • 9
    almost a copy of what the OP has described as not working
    – user829755
    Sep 29, 2015 at 12:05
  • 20
    Do not use convert for postscript or PDF files unless you go from vector to raster and never go back. It is hard to overstate what a bad idea this is. Nov 29, 2015 at 0:01
22

Use pdftools from PyPI.

Download the tar.gz file and uncompress it and run the command like below

python pdftools-1.1.0/pdfmerge.py -o output.pdf -d file1.pdf file2.pdf file3 

You should install python3 before you run the above command

This tools support the below

  • add
  • insert
  • Remove
  • Rotate
  • Split
  • Merge
  • Zip

You can find more details on GitHub and it is open source

2
  • 1
    This is perfect. Using gs (all variants listed above), a simple merge of two PDFs, 2MB and 500Kb, was taking minutes to complete and resulting in a 40MB file! pdftools completes instantaneously with identical file size.
    – supergra
    Nov 16, 2018 at 18:47
  • Or you can install it anyway. Total size of dependencies is < 100 kb.
    – tejasvi88
    Jan 26, 2021 at 14:46
17

Apache PDFBox http://pdfbox.apache.org/

PDFMerger This application will take a list of pdf documents and merge them, saving the result in a new document.

usage: java -jar pdfbox-app-x.y.z.jar PDFMerger "Source PDF files (2 ..n)" "Target PDF file"

0
13

Although it's not a command line solution, it may help macos users:

  1. Select your PDF files
  2. Right-click on your highlighted files
  3. Select Quick actions > Create PDF
1
  • 1
    I wonder why it is so low. This is exactly what I was looking for. Thank you. May 5, 2022 at 20:49
9

You can use sejda-console, free and open source. Unzip it and run sejda-console merge -f file1.pdf file2.pdf -o merged.pdf

It preserves bookmarks, link annotations, acroforms etc.. it actually has quite a lot of options you can play with, just run sejda-console merge -h to see them all.

2
  • OMHO the best to tool to do these type of tasks
    – mario ruiz
    Apr 25, 2020 at 0:29
  • 1
    This is no longer open source Apr 2, 2021 at 14:31
9

I am biased being one of the developers of PyMuPDF (a Python binding of MuPDF).

You can easily do what you want with it (and much more). Skeleton code works like this:

#-------------------------------------------------
import fitz         # the binding PyMuPDF
fout = fitz.open()  # new PDF for joined output
flist = ["1.pdf", "2.pdf", ...]  # list of filenames to be joined

for f in flist:
    fin = fitz.open(f)  # open an input file
    fout.insertPDF(fin) # append f
    fin.close()

fout.save("joined.pdf")
#-------------------------------------------------

That's about it. Several options are available for selecting only pages ranges, maintaining a joint table of contents, reversing page sequence or changing page rotation, etc., etc.

We are on PyPi.

8

I used qpdf from terminal and work for me at Windows (Mobaxterm) and Linux, for example the command for join A.pdf with B.pdf at new file C.pdf is:

qpdf --empty --pages oficios/A.pdf informes/B.pdf -- salida/C.PDF

If need more documentation [https://net2.com/how-to-merge-or-split-pdf-files-on-linux/][1]

3
  • 2
    This is quite the undervalued answer. The qpdf tool is great Mar 28, 2021 at 15:42
  • it's true, qpdf is multi platform, portable and possible used at scripts
    – Doberon
    Apr 3, 2021 at 0:53
  • for extract qpdf "in.pdf" --pages . 1 -- "out.pdf"
    – Doberon
    May 5, 2021 at 0:51
8

I second the pdfunite recommendation. I was however getting Argument list too long errors as I was attempting to merge > 2k PDF files.

I turned to Python for this and two external packages: PyPDF2 (to handle all things PDF related) and natsort (to do a "natural" sort of the directory's file names). In case this can help someone:

from pathlib import Path
from PyPDF2 import PdfMerger
import natsort

DIR = Path("dir-with-pdfs/")
OUTPUT = "output.pdf"

paths = DIR.glob("*.pdf")
paths = natsort.natsorted(paths)

merger = PdfMerger()

for path in paths:
    merger.append(path)

merger.write(OUTPUT)
2
  • 6
    "Argument list too long" indicates that you're going over the shell's allocated buffer size for the environment -- it's not actually a limitation of the tool. In such a case, switching to Python may be overkill, since you can just batch: find input -name *.pdf | xargs -P1 -n500 sh -c 'pdfunite "$@" output-date +%s.pdf' && pdfunite output-*.pdf output.pdf (This will create batches of 500 files processed serially, make the resulting temporary files sort in the right order, and produce an appropriate output file; you'll need to clean up the temporary files after)
    – enkiv2
    Nov 1, 2017 at 11:30
  • pdftools is a wrapper for PyPDF2. See this answer.
    – tejasvi88
    Jan 26, 2021 at 14:48
5

If you want to convert all the downloaded images into one pdf then execute

convert img{0..19}.jpg slides.pdf

1
  • 8
    Do not use convert for postscript or PDF files unless you go from vector to raster and never go back. It is hard to overstate what a bad idea this is. Nov 29, 2015 at 0:02
5

You can see use the free and open source pdftools (disclaimer: I am the author of it).

It is basically a Python interface to the Latex pdfpages package.

To merge pdf files one by one, you can run:

pdftools --input-file file1.pdf --input-file file2.pdf --output output.pdf

To merge together all the pdf files in a directory, you can run:

pdftools --input-dir ./dir_with_pdfs --output output.pdf
4

Here is a Bash script which checks for merging errors.

I had the problem that a few PDF merges produced some error messages. As it is quite a lot trial and error to find the corrupt PDFs, I wrote a script for it.

The following Bash script merges all available PDFs in a folder one by one and gives a success status after each merge. Just copy it in the folder with the PDFs and execute from there.

#!/bin/bash

PDFOUT=_all_merged.pdf
rm -f "${PDFOUT}"

for f in *.pdf
do
  printf "processing %-50s" "$f  ..." >&2
  if [ -f "$PDFOUT" ]; then
    # https://stackoverflow.com/questions/8158584/ghostscript-to-merge-pdfs-compresses-the-result
    #  -dPDFSETTINGS=/prepress
    status=$(gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="${PDFOUT}.new" "${PDFOUT}" "$f" 2> /dev/null)
    if [ "$status" ]
    then
      echo "gs ERROR: $status" >&2
    else
      echo "successful" >&2
    fi
    mv "${PDFOUT}.new" "${PDFOUT}"
  else
    cp "$f" "${PDFOUT}"
    echo "successful" >&2
  fi
done

example output:

processing inp1.pdf  ...                                     successful
processing inp2.pdf  ...                                     successful
3

Here's a method I use which works and is easy to implement. This will require both the fpdf and fpdi libraries which can be downloaded here:

require('fpdf.php');
require('fpdi.php');

$files = ['doc1.pdf', 'doc2.pdf', 'doc3.pdf'];

$pdf = new FPDI();

foreach ($files as $file) {
    $pdf->setSourceFile($file);
    $tpl = $pdf->importPage(1, '/MediaBox');
    $pdf->addPage();
    $pdf->useTemplate($tpl);
}

$pdf->Output('F','merged.pdf');
2

PdfCpu works great:

pdfcpu merge c.pdf a.pdf b.pdf

https://pdfcpu.io/core/merge

1
  • can be installed with homebrew +1 havent tried yet Mar 11, 2021 at 23:52
1

If you want to join all PDF files in a directory with Ghostscript, you can use find to do just that. Here's an example

find . -name '*.pdf' -exec gs -o -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile=../out.pdf {} +

Will find all pdf in current directory, and create out.pdf in parent directory. Might be useful if they're looking for a quick way for do an entire directory with ghostscript.

1
pdfconcat -o out.pdf 1.pdf 2.pdf

``pdfconcat is a small and fast command-line utility written in ANSI C that can concatenate (merge) several PDF files into a long PDF document.''

0

I like the idea of Chasmo, but I preffer to use the advantages of things like

convert $(ls *.pdf) ../merged.pdf

Giving multiple source files to convert leads to merging them into a common pdf. This command merges all files with .pdfextension in the actual directory into merged.pdf in the parent dir.

6
  • 5
    Given how similar this looks to the original question, it seems like this should have been a comment, not an answer. With a bit more rep, you will be able to post comments. Until then, please do not use answers as a workaround. May 16, 2015 at 2:02
  • 1
    @Silfheed No, it answers the question! Although the answer maybe should have more elaborated.
    – peterh
    May 16, 2015 at 8:33
  • 7
    Do not use convert for postscript or PDF files unless you go from vector to raster and never go back. It is hard to overstate what a bad idea this is. Nov 29, 2015 at 0:02
  • 15
    What is the point of using $(ls *.pdf) in place of simple wildcard *.pdf? Dec 18, 2015 at 4:56
  • 1
    Additionally with reference to @firegurafiku answer, with ls *.pdf wildcard you lose a control over the order of merged files. In an example, the following list: 1.pdf, 2.pdf, 3.pdf, ..., 10.pdf, ..., 100.pdf will actually be merged like 1.pdf, 10.pdf, 100.pdf, 2.pdf, 3.pdf (due to default Linux way of ordering files - here you have more details about this problem - stackoverflow.com/q/22948042/1977012).
    – Egel
    Jun 28, 2018 at 8:31
0

Yet another option, useful is you want to select also the pages inside the documents to be merged:

pdfjoin image.jpg '-' doc_only_first_pages.pdf '1,2' doc_with_all_pages.pdf '-'

It comes with package texlive-extra-utils

2
  • The package name probably refers to a Debian package.
    – tripleee
    Aug 2, 2021 at 8:50
  • I'm running Debian GNU/Linux 11 (bullseye) and have texlive-extra-utils installed, yet pdfjoin is not found on my system. My texlive-extra-utils is version 2020.20210202-3. Any idea why this is the case? Are you actually referring to the Debian distribution of texlive? That should be added to your answer.
    – GPWR
    Oct 21, 2022 at 17:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.