在 Java 中向 PDF 添加线形状
Contents
[
Hide
]
添加虚线
- 创建一个新的 PDF Document。
- 将一个 Page 添加到文档。
- 创建一个 Graph 容器并将其添加到页面。
- 创建 Line 形状并配置其坐标。
- 添加 Line 到 Graph 容器。
- 保存输出的 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());
}
}
添加彩色点线或虚线
addDottedDashedLine 使用相同的坐标和虚线设置,但也应用 Color.getRed()。
在页面上绘制线条
- 创建一个新的 PDF Document。
- 将一个 Page 添加到文档。
- 创建一个 Graph 容器并将其添加到页面。
- 创建 Line 形状并配置其坐标。
- 添加 Line 到 Graph 容器。
- 保存输出的 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());
}
}