2011-05-18 83 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