2016-08-05 99 views
0

我需要在現有的pdf上繪製一個矩形。這是我做的如何在現有pdf上繪製幾何圖形?

public class Main { 


    public static void main(String[] args) throws IOException { 

     String originalFile = "C:\\Users\\original.pdf"; 
     String modifiedFile = "C:\\Users\\modified.pdf"; 

     PDDocument doc = PDDocument.load(new File(originalFile)); 
     PDPage page = (PDPage) doc.getDocumentCatalog().getPages().get(0); 

     PDPageContentStream contentStream = new PDPageContentStream(doc, page ); 
     drawRect(contentStream, Color.green, new java.awt.Rectangle(500, 500, 20, 200), true); 
     contentStream.close(); 
     doc.save(new File(modifiedFile)) ; 

    } 



    private static void drawRect(PDPageContentStream content, Color color, Rectangle rect, boolean fill) throws IOException { 
     content.addRect(rect.x, rect.y, rect.width, rect.height); 
     if (fill) { 
      content.setNonStrokingColor(color); 
      content.fill(); 
     } else { 
      content.setStrokingColor(color); 
      content.stroke(); 
     } 
    } 


} 

但是,這會在空白頁面上創建一個綠色的矩形。我需要現有數據頂部的矩形。我能正確保存嗎?

回答

2

請改變這一行

PDPageContentStream contentStream = new PDPageContentStream(doc, page ); 

這樣:

PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true); 

這不僅創造額外的內容流,而且重置圖形上下文。