2013-02-08 126 views
1

我想將一個2x2 pdf文檔分成它的原始頁面。每個頁面由4個邏輯頁面組成,這些頁面的排列方式與示例中的this類似。如何拆分每張紙上包含多個邏輯頁面的pdf文檔?

我試圖使用pythonpypdf

import copy, sys 
from pyPdf import PdfFileWriter, PdfFileReader 

def ifel(condition, trueVal, falseVal): 
    if condition: 
     return trueVal 
    else: 
     return falseVal 

input = PdfFileReader(file(sys.argv[1], "rb")) 
output = PdfFileWriter() 

for p in [input.getPage(i) for i in range(0,input.getNumPages())]: 
    (w, h) = p.mediaBox.upperRight 

    for j in range(0,4): 
     t = copy.copy(p)   
     t.mediaBox.lowerLeft = (ifel(j%2==1, w/2, 0), ifel(j<2, h/2, 0)) 
     t.mediaBox.upperRight = (ifel(j%2==0, w/2, w), ifel(j>1, h/2, h)) 
     output.addPage(t) 

output.write(file("out.pdf", "wb")) 

不幸的是,預期的,因爲它四次每次輸出第四邏輯頁這個腳本不起作用。由於我之前沒有在python中寫過任何東西,我認爲這是一個非常基本的問題,大概是由於複製操作。我真的很感激任何幫助。


編輯:嗯,我也做了一些實驗。我手動插入頁面的寬度和高度,如以下:

import copy, sys 
from pyPdf import PdfFileWriter, PdfFileReader 

def ifel(condition, trueVal, falseVal): 
    if condition: 
     return trueVal 
    else: 
     return falseVal 

input = PdfFileReader(file(sys.argv[1], "rb")) 
output = PdfFileWriter() 

for p in [input.getPage(i) for i in range(0,input.getNumPages())]: 
    (w, h) = p.mediaBox.upperRight 

    for j in range(0,4): 
     t = copy.copy(p)   
     t.mediaBox.lowerLeft = (ifel(j%2==1, 841/2, 0), ifel(j<2, 595/2, 0)) 
     t.mediaBox.upperRight = (ifel(j%2==0, 841/2, 841), ifel(j>1, 595/2, 595)) 
     output.addPage(t) 

output.write(file("out.pdf", "wb")) 

此代碼導致同一錯誤結果作爲我原來的一個,如果我現在註釋掉該行(w, h) = p.mediaBox.upperRight,一切正常!我找不到任何理由。元組(w, h)甚至不再使用,那麼如何移除它的定義會改變什麼?

回答

0

我懷疑問題是mediaBox只是一個魔術訪問器,因爲變量是通過p和所有副本t共享的。因此,分配給t.mediaBox將導致mediaBox在所有四個副本中具有相同的座標。

第一次訪問mediaBox時mediaBox字段後面的變量是懶惰創建的,所以如果你註釋掉(w, h) = p.mediaBox.upperRight這一行,mediaBox變量將爲每個t單獨創建。自動確定頁面尺寸

兩個可能的解決方案:

  1. 製作副本後獲得的尺寸:

    for p in [input.getPage(i) for i in range(0,input.getNumPages())]: 
    
        for j in range(0,4): 
         t = copy.copy(p)  
         (w, h) = t.mediaBox.upperRight 
         t.mediaBox.lowerLeft = (ifel(j%2==1, w/2, 0), ifel(j<2, h/2, 0)) 
         t.mediaBox.upperRight = (ifel(j%2==0, w/2, w), ifel(j>1, h/2, h)) 
         output.addPage(t) 
    
  2. 實例化新RectangleObjects用於媒體框變量

    for p in [input.getPage(i) for i in range(0,input.getNumPages())]: 
        (w, h) = p.mediaBox.upperRight 
    
        for j in range(0,4): 
         t = copy.copy(p)   
         t.mediaBox.lowerLeft = pyPdf.generic.RectangleObject(
                ifel(j%2==1, w/2, 0), 
                ifel(j<2, h/2, 0), 
                ifel(j%2==0, w/2, w), 
                ifel(j>1, h/2, h)) 
         output.addPage(t) 
    

使用copy.deepcopy()將導致大型複雜PDF的內存問題,

相關問題