Search code examples
pythonpdfpdf-generationpypdf

Shrink and merge PDFs in Python


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!


Solution

  • 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)