5

我无法将两个 PDF 文件与 pyPdf 合并。当我运行以下代码时,水印(page1)看起来不错,但 page2 已顺时针旋转 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()
4

5 回答 5

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)
于 2013-06-30T17:10:57.603 回答
2

我找到了解决方案。我的代码很好——我只需要更改生成原始 PDF 文件的方式。

我没有使用 PdfCreator 和 Photoshop 创建 PDF,而是将我的 Photoshop 图像复制并粘贴到 MS Word 2007 中,然后使用它的导出功能为 page1 创建 PDF 文件。现在效果很好!

因此,PdfCreator 必须生成与 pyPdf 不兼容的 PDF 文件。

于 2011-05-19T01:19:49.817 回答
0

You can make use of the rotateClockwise or rotataeCounterClockwise function in the page object.

page2 = input2.getPage(0).rotateCounterClockwise(90)
于 2011-05-18T07:35:40.120 回答
0

我想补充一点,我使用 Photoshop 保存 PDF,但与 1.4 版兼容。这制作了一个巨大的 PDF 文件,但它确实有效。

所以它是 pyPDF 没有正确阅读它。

于 2013-03-30T21:58:39.950 回答
0

由于您使用的是 pyPdf,因此这应该可以解决旋转页面的问题:

output.addPage(input1.getPage(1).rotateClockwise(90))
于 2011-11-24T20:44:00.440 回答