PDF pages can't be properly merged

Viewed 23

I have 2 PDF files, each containing only one page, both pages are in same size and same orientation (landscape). I tried to use reportlab to merge theses 2 pages and save the result to a new pdf file. But the result is confusing. Each time I tried to merge, one of the pages is some how rotated by 90 degree.

Here is the code, does anybody know what I've done wrong:

base_pdf = PdfFileReader(open("base.pdf", "rb"))
hello_pdf = PdfFileReader(open("hello.pdf", "rb"))

new_pdf = PdfFileWriter()
base_page = base_pdf.getPage(0)
hello_page = hello_pdf.getPage(0)
base_page.mergePage(hello_page)

new_pdf.addPage(base_page)


outputStream = open("merged.pdf", "wb")
new_pdf.write(outputStream)
outputStream.close()
1 Answers

Each page in a PDF file can be rotated, on-the-fly, when a PDF viewer loads it, by 90 degrees, 180 degrees, or 270 degrees.

One of your PDFs has pages which are genuinely landscape. The other has portrait pages with /Rotate set to 90 or 270.

The software you are using is deliberately or accidentally not taking account of the difference when overlaying one page over the other.

You can use cpdf to regularize the rotated file prior to processing with your library. This will remove the soft rotation, and counter-rotate the page dimensions and content to compensate:

cpdf -upright in.pdf -o out.pdf

If you look into the documentation of the PDF library you are already using, you might find a way to do it there too.

Related