john john - 10 months ago 49
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,, new java.awt.Rectangle(500, 500, 20, 200), true);
contentStream.close(); 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) {
} else {


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?


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.