gpt4 book ai didi

python - 如何使用 pyPdf 合并两个横向 pdf 页面

转载 作者:太空狗 更新时间:2023-10-30 00:57:38 25 4
gpt4 key购买 nike

我在用 pyPdf 合并两个 PDF 文件时遇到问题。当我运行以下代码时,水印 (page1) 看起来不错,但 page2 已顺时针旋转 90 度。

有什么想法吗?

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

最佳答案

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

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)

关于python - 如何使用 pyPdf 合并两个横向 pdf 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6041244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com