Hum*_*rey 5 python pdf-generation landscape pypdf
我在使用pyPdf合并两个PDF文件时遇到问题.当我运行以下代码时,水印(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()
Run Code Online (Sandbox Code Playgroud)
您可以在将页面合并到另一页面时对页面进行转换.我定义了这个函数,在合并时围绕一个点旋转页面:
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]])
Run Code Online (Sandbox Code Playgroud)
然后你这样称呼它:
mergeRotateAroundPointPage(page1, page2,
page1.get('/Rotate') or 0,
page2.mediaBox.getWidth()/2, page2.mediaBox.getWidth()/2)
Run Code Online (Sandbox Code Playgroud)
我找到了解决方案。我的代码很好 - 我只需要更改生成原始 PDF 文件的方式。
我没有使用 PdfCreator 和 Photoshop 创建 PDF,而是将 Photoshop 图像复制并粘贴到 MS Word 2007 中,然后使用它的导出功能为 page1 创建 PDF 文件。现在效果很好!
因此,PdfCreator 必须生成与 pyPdf 不兼容的 PDF 文件。