使用 Apache PDFBox 将实心圆添加到 PDF 页面

Adding of filled circles to PDF page using Apache PDFBox

我正在尝试使用 Apache PDFBox library to create a PDF document programmatically. The class PDPageContentStream 包含的方法来编写文本、绘制线条、贝塞尔曲线、矩形。但是我找不到画一个简单的实心圆的方法。有没有办法使用这个库来绘制它?如果没有,能否推荐一个免费的 Java 库,它提供灵活的 API 以编程方式创建 PDF 文档?提前致谢。

所以,我 运行 解决了这个问题,并且有办法,但是它有点作弊并且取决于你想做什么,不是一个好的解决方案。您可以利用包含圆形类型的 PDF "annotations",例如:

PDAnnotationSquareCircle circle = new PDAnnotationSquareCircle(PDAnnotationSquareCircle.SUB_TYPE_CIRCLE);
PDRectangle position = new PDRectangle();
position.setLowerLeftX(0);
position.setLowerLeftY(0;
position.setUpperRightX(100);
position.setUpperRightY(100);
circle.setRectangle(position);

然后调用

circle.SetInteriorColor(someCOSColor);

用颜色作为填充它的参数。这个问题是,它是一个 "annotation",除非您锁定文档以进行编辑,否则人们可以将它们拖来拖去。此外,如果 Windows 上的人尝试打印它们,他们将看不到注释。使用风险自负,但它会给你实心彩色圆圈

编辑:添加了更完整的示例以回应评论

好的,谢谢大家的回复。我喜欢贝塞尔曲线的解决方案。这种方法对我有用:

private void drawCircle(PDPageContentStream contentStream, int cx, int cy, int r, int red, int green, int blue) throws IOException {
    final float k = 0.552284749831f;
    contentStream.setNonStrokingColor(red, green, blue);
    contentStream.moveTo(cx - r, cy);
    contentStream.curveTo(cx - r, cy + k * r, cx - k * r, cy + r, cx, cy + r);
    contentStream.curveTo(cx + k * r, cy + r, cx + r, cy + k * r, cx + r, cy);
    contentStream.curveTo(cx + r, cy - k * r, cx + k * r, cy - r, cx, cy - r);
    contentStream.curveTo(cx - k * r, cy - r, cx - r, cy - k * r, cx - r, cy);
    contentStream.fill();
}