2014-02-21 49 views
0

我試圖通過向每個頁面的標題添加一些文本來修改現有的PDF。但是,即使是簡單的示例代碼我具有低於最終產生我一個空白PDF作爲輸出:打開內容流會保存內容空白嗎?

document = PDDocument.load(new File("c:/tmp/pdfbox_test_in.pdf")); 
    PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(0); 

    PDPageContentStream contentStream = new PDPageContentStream(document, page); 

    /* 
    contentStream.beginText(); 
    contentStream.setFont(font, 12); 
    contentStream.moveTextPositionByAmount(100, 100); 
    contentStream.drawString("Hello"); 
    contentStream.endText(); 
    */ 

    contentStream.close(); 

    document.save("c:/tmp/pdfbox_test_out.pdf"); 
    document.close(); 

(註釋的塊相同的結果是否執行或沒有)。

那麼,如何簡單地打開內容流並關閉足夠的空白保存的文件?是否還有其他API調用需要進行以避免內容被剝離?

令人驚訝的是,我找不到這種改變的PDFBox配方。

回答

3

您使用

PDPageContentStream contentStream = new PDPageContentStream(document, page); 

此構造是這樣實現的:

public PDPageContentStream(PDDocument document, PDPage sourcePage) throws IOException 
{ 
    this(document, sourcePage, false, true); 
} 

進而調用這個

/** 
* Create a new PDPage content stream. 
* 
* @param document The document the page is part of. 
* @param sourcePage The page to write the contents to. 
* @param appendContent Indicates whether content will be overwritten. If false all previous content is deleted. 
* @param compress Tell if the content stream should compress the page contents. 
* @throws IOException If there is an error writing to the page contents. 
*/ 
public PDPageContentStream(PDDocument document, PDPage sourcePage, boolean appendContent, boolean compress) throws IOException 

所以兩個 - 參數構造函數始終使用appendContent = false,這會導致全部以前的內容刪除

因此,你應該使用

PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true); 

追加到當前內容。

0

呃,顯然我們在項目中使用的PDFBox版本需要升級。我只注意到最新的API有我需要的構造函數:

public PDPageContentStream(PDDocument document, PDPage sourcePage, boolean appendContent, boolean compress) 

所以改變這種構造和使用appendContent = true時,我得到了上述樣品的工作。 時間進行升級...

+0

哦,你在我寫答案的時候發現了它......;) – mkl