Add Line Shapes to PDF in Java

Add a dashed line

  1. Create a new PDF Document.
  2. Add a Page to the document.
  3. Create a Graph container and add it to the page.
  4. Create the Line shape and configure its coordinates.
  5. Add the Line to the Graph container.
  6. Save the output PDF Document.
public static void addLine(Path outputFile) {
    try (Document document = new Document()) {
        Page page = document.getPages().add();
        Graph graph = new Graph(100.0, 400.0);
        page.getParagraphs().add(graph);

        Line line = new Line(new float[]{100, 100, 200, 100});
        line.getGraphInfo().setDashArray(new int[]{0, 1, 0});
        line.getGraphInfo().setDashPhase(1);
        graph.getShapes().addItem(line);

        document.save(outputFile.toString());
    }
}

Add a colored dotted or dashed line

addDottedDashedLine uses the same coordinates and dash settings, but also applies Color.getRed().

Draw lines across the page

  1. Create a new PDF Document.
  2. Add a Page to the document.
  3. Create a Graph container and add it to the page.
  4. Create the Line shape and configure its coordinates.
  5. Add the Line to the Graph container.
  6. Save the output PDF Document.
public static void drawLineAcrossPage(Path outputFile) {
    try (Document document = new Document()) {
        Page page = document.getPages().add();
        page.getPageInfo().getMargin().setLeft(0);
        page.getPageInfo().getMargin().setRight(0);
        page.getPageInfo().getMargin().setBottom(0);
        page.getPageInfo().getMargin().setTop(0);

        Graph graph = new Graph(page.getPageInfo().getWidth(), page.getPageInfo().getHeight());
        Line line = new Line(new float[]{
                (float) page.getRect().getLLX(),
                0,
                (float) page.getPageInfo().getWidth(),
                (float) page.getRect().getURY()
        });
        graph.getShapes().addItem(line);
        page.getParagraphs().add(graph);

        document.save(outputFile.toString());
    }
}