Search code examples
pdfmergeghostscript

ghostscript: how to marge in a single pdf different pages from multiple pdf


I'm trying using ghostscript to merge only certain page from multiple pdfs files to a single pdf file. Is possible to do it? I just try:

'/usr/local/bin/gs' '-dBATCH' '-dNOPAUSE' -q -sDEVICE=pdfwrite -sOutputFile=finished.pdf pdf1.pdf pdf2.pdf ...

it works, but merge all pdf pages. I need only someone.

ES: PDF1.pdf with 5 pages PDF2.pdf with 10 pages

i like to have a finished.pdf with page 1 of PDF1.pdf and page 3 of PDF2.pdf..


Solution

  • Firstly, as I keep saying, Ghostscript (and the pdfwrite device) do not 'merge', 'concatenate', 'modify', 'edit' or whatever, PDF files.

    When you supply input to Ghostscript it fully interprets it, producing a sequence of graphics primitives, which it then passes to the device. In the case of low level devices, these use the graphics library to render the primitive to a bitmap. The high level (or vector) devices create an equivalent to the graphic primitives in whatever output format they are creating, and output that.

    So, the output from pdfwrite is a PDF file. The internals of that PDF file bear no relation to the input, even if the input was a PDF file. The only thing that is expected is that the appearance should be equivalent.

    That said, a great deal of 'metadata' is extracted from PDF files by the PDF interpreter, and passed on to the pdfwrite device, so it 'looks like' the PDF is the same. But you must be aware that the PDF file you get out is not the one you started with.

    Now, Ghostscript's PDF interpreter can only handle one PDF file at a time. So there's no way to interpret a page from one PDF file, then a page from another PDF file, then a page form the first and so on.

    The only way to do what you want to, using Ghostscript, is to create a single PDF file for each page of each file that you want to deal with (set OutputFile=%d.pdf to create one PDF per page) then run Ghostscript again, feeding each page sequentially, in the desired order, to Ghostscript. Because you are now only dealing with one PDF file at a time, this will work.

    Or, you could look at a tool which is intended for this kind of work, which Ghostscript really isn't.