john john - 4 months ago 23
Java Question

How draw geometric figures on top on an existing pdf?

I need to draw a rectangle on top of an existing pdf. Here is what i do

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();
}
}


}


However this creates a green rectangle on a blank page. I need that rectangle on top of the existing data. Do I save it correctly?

Answer

Please change this line

PDPageContentStream contentStream = new PDPageContentStream(doc, page  ); 

to this:

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

this will not only create an extra content stream, but also reset the graphics context.

Comments