How to combine two pages in pdf using pyPdf

I'm having trouble merging two PDF files with pyPdf. When I run the following code, the watermark (page 1) looks fine, but page2 is rotated 90 degrees clockwise.

Any ideas what is going on?

Example of what's going wrong

from pyPdf import PdfFileWriter, PdfFileReader

# PDF1: A4 Landscape page created in photoshop using PdfCreator, 
input1 = PdfFileReader(file("base.pdf", "rb"))
page1 = input1.getPage(0)

# PDF2: A4 Landscape page, text only, created using Pisa (www.xhtml2pdf.com)
input2 = PdfFileReader(file("text.pdf", "rb"))
page2 = input2.getPage(0)

# Merge
page1.mergePage(page2)

# Output
output = PdfFileWriter()
output.addPage(page1)
outputStream = file("output.pdf", "wb")
output.write(outputStream)
outputStream.close()
+5
source share
5 answers

I have found a solution. My code was fine - I just had to change the way I created the PDF source files.

Instead of creating a PDF file using PdfCreator and Photoshop, I copied and pasted my Photoshop image into MS Word 2007, and then used its export function to create a PDF file for page1. Now it works great!

, PdfCreator PDF, pyPdf.

+2

. :

def mergeRotateAroundPointPage(page, page2, rotation, tx, ty):
    translation = [[1, 0, 0],
                   [0, 1, 0],
                   [-tx,-ty,1]]
    rotation = math.radians(rotation)
    rotating = [[math.cos(rotation), math.sin(rotation),0],
                [-math.sin(rotation),math.cos(rotation), 0],
                [0,                  0,                  1]]
    rtranslation = [[1, 0, 0],
                   [0, 1, 0],
                   [tx,ty,1]]
    ctm = utils.matrixMultiply(translation, rotating)
    ctm = utils.matrixMultiply(ctm, rtranslation)

    return page.mergeTransformedPage(page2, [ctm[0][0], ctm[0][1],
                                             ctm[1][0], ctm[1][1],
                                             ctm[2][0], ctm[2][1]])

:

mergeRotateAroundPointPage(page1, page2, 
                page1.get('/Rotate') or 0, 
                page2.mediaBox.getWidth()/2, page2.mediaBox.getWidth()/2)
+5

rotateClockwise rotataeCounterClockwise .

page2 = input2.getPage(0).rotateCounterClockwise(90)
0

pyPdf, :

output.addPage(input1.getPage(1).rotateClockwise(90))
0

, Photoshop PDF , 1.4. PDF , .

pyPDF .

0

All Articles