我有这样一个圆圈的代码,我需要向这个圆圈的中心添加文本,但我不知道该怎么做
private static @NotNull PdfCanvas getPdfCanvas(PdfDocument pdf) {
int centerX = 300;
int centerY = 550;
int radius = 100;
float fillPercent = 98;
float circleThickness = 10;
float arcThickness = 15;
PdfCanvas canvas = new PdfCanvas(pdf, 1);
canvas.setFillColor(ColorConstants.GRAY);
canvas.circle(centerX, centerY, radius);
canvas.fill();
canvas.setFillColor(ColorConstants.WHITE);
canvas.circle(centerX, centerY, radius - circleThickness);
canvas.fill();
canvas.setStrokeColor(ColorConstants.RED);
canvas.setLineWidth(arcThickness);
canvas.arc(centerX - radius + circleThickness / 2, centerY - radius + circleThickness / 2,
centerX + radius - circleThickness / 2, centerY + radius - circleThickness / 2, 90, -fillPercent / 100 * 360.);
return canvas;
}
我尝试使用这样的代码,但它对我没有帮助。
Rectangle rect = new Rectangle(centerX, centerY, 500, 500);
Canvas textCanvas = new Canvas(canvas, rect, false);
textCanvas.showTextAligned(new Paragraph("text").setFontSize(12), centerX, centerY, TextAlignment.CENTER);
首先,下次请考虑分享您正在使用哪个库以及哪个版本。我使用
itextpdf
库和这些依赖项测试了代码:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-core</artifactId>
<version>8.0.2</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>bouncy-castle-adapter</artifactId>
<version>8.0.2</version>
</dependency>
基于 itext 的官方 github 存储库。而且我没有看到任何
showTextAligned()
方法,它不存在。然而有一种方法叫做showText()
。以下是如何使用此方法来实现您想要的目标:
// Add text in the middle of the circle
String text = "Centered Text";
canvas.setFillColor(ColorConstants.RED);
PdfFont font = PdfFontFactory.createFont();
canvas.beginText();
canvas.setFontAndSize(font, 12);
// Calculate text width and height
float textWidth = font.getWidth(text, 12);
float textHeight = 12;
// Calculate position to center the text
float textX = centerX - (textWidth / 2);
float textY = centerY - (textHeight / 2);
canvas.moveText(textX, textY);
canvas.showText(text);
canvas.endText();
我相信代码上的注释行是非常不言自明的。在代码末尾的 return 语句之前添加此代码。
它看起来像这样: pdf
希望这有帮助。