2011-05-18 84 views
5

我无法合并两个PDF文件与pyPdf。当我运行以下代码时,水印(page1)看起来很好,但page2已顺时针旋转90度。如何使用pyPdf合并两个横向PDF页面

任何想法发生了什么?

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

你确定他们都是风景?它看起来像左边是肖像。 – 2011-05-18 07:32:10

+0

是的,他们是 - 我刚刚创建该图像作为我的实际PDF联系人个人身份信息的示例。 – Humphrey 2011-05-19 01:14:42

+0

我有问题'pisaContext实例没有属性'seek'' – andi 2014-11-12 14:10:31

回答

2

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

不使用PdfCreator创建PDF & Photoshop,我复制并粘贴我的Photoshop图像到MS Word 2007中,然后使用它的导出功能为page1创建PDF文件。它现在很好用!

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

0

您可以在页面中使用对象的rotateClockwise或rotataeCounterClockwise功能。

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

是的,我已经尝试过这样做。但是,它不起作用!这两页仍然有90度的不同。我开始认为在pyPdf中有一个bug,或者在我的page1 pdf文件中发生了一些奇怪的事情。 – Humphrey 2011-05-19 01:08:01

0

由于您使用pyPdf,这应该做的伎俩旋转页面:

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

我想补充一点,我使用的Photoshop保存的PDF,但1.4版本兼容。这做了一个巨大的PDF文件,但它的工作。

所以这是pyPDF不正确的读取它。

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) 
+0

更新:我很高兴地说,这段代码已经合并到主线pyPDF2存储库中,所以没有更多的复制粘贴,只需调用它! – speedplane 2014-05-15 04:59:26

+2

更新2:它在PyPDF2中的名称现在是'mergeRotatedTranslatedPage'。我们在PyPDF中发现了这个文档不清楚,但将其理解为“旋转点”是有道理的。 – mwakerman 2017-09-29 04:42:20