Shrink and merge PDFs in Python

Question:

I’m trying to shrink and merge two A4 PDF pages into one A4 page so that if I had;

 _____        _____        
|     |      |     |
| p1  |      | p2  | 
|     |      |     |
|_____|      |_____|
         

I would get;

 _____             
| p1  |    
|.....| 
| p2  |  
|_____|      

As a new PDF, with two A5 sized pages on that one page. Similar to how you might print two pages per page on paper.

I’ve looked into pypdf and ReportLab but I can’t seem to find how to shrink and merge like this.

Any hints?

Thanks!

Asked By: Danny King

||

Answers:

The way I would do it (not necessarily the best way, but using tools I have available) would be to use Ghostcript’s pdf2ps to convert to PostScript, then append an N-up PostScript preamble (PS is a full programming language and you can redefine builtins like “showpage” to add N-up or posterization directly to a document) and then I’d convert back with ps2pdf.

Offhand I’m not finding a published version of a PostScript N-up utility, but you can google several ones written in other languages that manipulate the PostScript document itself, such as those at http://www.tardis.ed.ac.uk/~ajcd/psutils/

Answered By: Ben Jackson

pdfnup has this functionality (http://pypi.python.org/pypi/pdfnup)#

e.g.

from pyPdf import PdfFileWriter, PdfFileReader
from pdfnup import generateNup

output = PdfFileWriter()
input1 = PdfFileReader(file("in.pdf", "rb"))

page1 = input1.getPage(0)
page2 = input1.getPage(1)

output.addPage(page1)
output.addPage(page2)

outputStream = file("out.pdf", "wb")
output.write(outputStream)
outputStream.close()

generateNup("out.pdf", 2)
Answered By: Danny King
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.