如何用pyPdf合并两页横向PDF

5 投票
5 回答
7283 浏览
提问于 2025-04-16 17:52

我在用pyPdf合并两个PDF文件时遇到了问题。当我运行下面的代码时,水印(第一页)看起来没问题,但第二页却顺时针旋转了90度。

有人知道这是怎么回事吗?

出现问题的示例

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 个回答

0

你可以在页面对象中使用rotateClockwise或者rotateCounterClockwise这两个函数。

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

你可以在把一个页面合并到另一个页面的时候,对这个页面进行一些变换。我定义了一个函数,可以在合并的时候围绕一个点旋转这个页面:

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

我找到了解决办法。我的代码没问题,只是我生成原始PDF文件的方法需要改一下。

我没有再用PdfCreator和Photoshop来制作PDF,而是把Photoshop里的图片复制粘贴到MS Word 2007里,然后用它的导出功能来生成第一页的PDF文件。现在效果很好!

所以,PdfCreator生成的PDF文件可能和pyPdf不兼容。

撰写回答