Add Line Shapes to PDF in Java
Contents
[
Hide
]
Add a dashed line
- Create a new PDF Document.
- Add a Page to the document.
- Create a Graph container and add it to the page.
- Create the Line shape and configure its coordinates.
- Add the Line to the Graph container.
- 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
- Create a new PDF Document.
- Add a Page to the document.
- Create a Graph container and add it to the page.
- Create the Line shape and configure its coordinates.
- Add the Line to the Graph container.
- 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());
}
}