如何在现有 pdf 的顶部绘制几何图形?
How draw geometric figures on top on an existing pdf?
我需要在现有 pdf 上绘制一个矩形。这就是我所做的
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, Color.green, new java.awt.Rectangle(500, 500, 20, 200), true);
contentStream.close();
doc.save(new 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) {
content.setNonStrokingColor(color);
content.fill();
} else {
content.setStrokingColor(color);
content.stroke();
}
}
}
然而,这会在空白页上创建一个绿色矩形。我需要现有数据之上的那个矩形。我保存正确吗?
请更改此行
PDPageContentStream contentStream = new PDPageContentStream(doc, page );
对此:
PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
这不仅会创建额外的内容流,还会重置图形上下文。
我需要在现有 pdf 上绘制一个矩形。这就是我所做的
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, Color.green, new java.awt.Rectangle(500, 500, 20, 200), true);
contentStream.close();
doc.save(new 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) {
content.setNonStrokingColor(color);
content.fill();
} else {
content.setStrokingColor(color);
content.stroke();
}
}
}
然而,这会在空白页上创建一个绿色矩形。我需要现有数据之上的那个矩形。我保存正确吗?
请更改此行
PDPageContentStream contentStream = new PDPageContentStream(doc, page );
对此:
PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
这不仅会创建额外的内容流,还会重置图形上下文。