[JAVA] Draw a line on an existing PDF document using PDFBox

I had a niche need to draw lines on an existing PDF document using PDFBox, so I'll show you how. For example, in the form of submission to the government, it is assumed that a strikethrough is drawn on irrelevant parts according to the content of the application.

image.png

Confirmation environment

Realization method

void line() throws IOException {
    try (InputStream is = getInputStream("sample.pdf");
         PDDocument doc = PDDocument.load(is)) {

        PDPage page = doc.getPage(0);
        PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, false);

        contents.moveTo(290f, 808f); //Start point coordinates
        contents.lineTo(365f, 808f); //End point coordinates
        contents.setLineWidth(1f);   //Line thickness
        contents.stroke();           //drawing

        contents.moveTo(290f, 805f); //Start point coordinates
        contents.lineTo(365f, 805f); //End point coordinates
        contents.setLineWidth(1f);   //Line thickness
        contents.stroke();           //drawing

        contents.close();
        doc.save("/tmp/output.pdf");
    }
}

Specifying the drawing position

There seems to be a smarter way, such as using the right tools, but I didn't know, so I decided to draw the coordinate system myself, which is muddy.

void grid() throws IOException {
    try (InputStream is = getInputStream("sample.pdf");
         PDDocument doc = PDDocument.load(is)) {
        PDPage page = doc.getPage(0);

        //Draw a grid from the bottom left to the top right of the page
        PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, false);
        PDRectangle bbox = page.getBBox();
        for (float x = 0; x < bbox.getWidth(); x += 10) {
            contents.moveTo(bbox.getLowerLeftX() + x, bbox.getLowerLeftY());
            contents.lineTo(bbox.getLowerLeftX() + x, bbox.getUpperRightY());
            contents.setLineWidth((x % 100 == 0) ? 2f : 0.5f);
            contents.stroke();
        }
        for (float y = 0; y < bbox.getHeight(); y += 10) {
            contents.moveTo(bbox.getLowerLeftX(), bbox.getLowerLeftY() + y);
            contents.lineTo(bbox.getUpperRightX(), bbox.getLowerLeftY() + y);
            contents.setLineWidth((y % 100 == 0) ? 2f : 0.5f);
            contents.stroke();
        }
        contents.close();

        doc.save("/tmp/output.pdf");
    }
}

After that, if you count the scale from the lower left, you can specify the rough coordinates of the position you want to draw.

image.png

If there is a better way, please let me know: sweat_smile:

Recommended Posts

Draw a line on an existing PDF document using PDFBox
[Swift 5] Draw a line.
Using a local network on iOS 14
I made an app to scribble with PencilKit on a PDF file
Duplicate an object using a generic type
Send an email using JavaMail on AWS