【问题标题】:How to merge two landscape pdf pages using pyPdf如何使用pyPdf合并两个横向pdf页面
【发布时间】:2011-08-27 19:52:32
【问题描述】:

我在将两个 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()

【问题讨论】:

  • 你确定它们都是横向的吗?左边的好像是纵向的。
  • 是的,他们是 - 我刚刚创建了该图像作为我实际 pdf 的联系人个人身份信息的示例。
  • 我对@9​​87654323@有疑问

标签: python pdf-generation landscape pypdf


【解决方案1】:

您可以在将页面合并到另一个页面时对其进行转换。我定义了这个函数来在合并时围绕一个点旋转页面:

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)

【讨论】:

  • 更新:我很高兴地说这段代码已经合并到主线pyPDF2存储库中,所以不再复制粘贴,只需调用它!
  • 更新 2:它在 PyPDF2 中的名称现在是 mergeRotatedTranslatedPage。我们发现 PyPDF 中的文档不清楚,但将其理解为“围绕点旋转”是有道理的。
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

      所以是 pyPDF 没有正确阅读。

      【讨论】:

        【解决方案5】:

        您可以在页面对象中使用 rotateClockwise 或 rotataeCounterClockwise 函数。

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

        【讨论】:

        • 是的,我已经尝试过这样做。但是,它不起作用!两页仍然相差 90 度。我开始认为 pyPdf 中存在错误,或者我的 page1 pdf 文件中发生了一些奇怪的事情。
        猜你喜欢
        • 1970-01-01
        • 2013-06-13
        • 2013-06-10
        • 2019-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-04
        • 2010-10-06
        相关资源
        最近更新 更多