Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a margin to pdf pages with PyPDF2

I am creating a python script that can modify a pdf file to be printed in book sections. As there is no such functionality in the ubuntu printing settings.

PyPDF2 is a wonderful tool with which I have been able to do everything I wanted except adding a margin.

For example consider this book.
http://www.edwardothorp.com/sitebuildercontent/sitebuilderfiles/beatthemarket.pdf It requires some margins so that there is some room for binding them in a book. I have found how to shift the content a few pixels, but the size of the "canvas" doesn't change so some content is cut off.

I am able to adjust the "page size" with PyPDF2 by changing the mediabox size but I an only crop the pages, I cannot increase their size. And to add margins, I have to increase the size. I also can't shrink the content, because then for some reason the page size shrinks with it.

Here is the script if you want to print a book. http://pastebin.com/LGYhKYu1 Of course, it only works with pdfs with already some margins so you only need to shift the content.

I would be most grateful if someone could point out how to add margins to a pdf with PyPDF2 , I must be overlooking something.

Thank you!

like image 218
Lerak Avatar asked Oct 05 '14 15:10

Lerak


1 Answers

It seems there is no dedicated method, but you can create an empty page of the desired size, then merge your content with the empty page

page = PageObject.createBlankPage(
        yourPage.mediaBox.getWidth () + 2 * margin,  
        yourPage.mediaBox.getHeight() + 2 * margin)
page.mergeScaledTranslatedPage( yourPage, scale, leftMargin, bottomMargin)    
...
output = PdfFileWriter()
output.addPage(page)
like image 67
brembo Avatar answered Sep 27 '22 23:09

brembo