【问题标题】:Placing text (numbers) at indicated positions在指定位置放置文本(数字)
【发布时间】:2018-09-17 14:34:04
【问题描述】:

使用 for 循环,我遍历存储在矩阵 X 中的一组坐标,并在指定位置绘制圆圈(使用 itextpdf):

...
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(fileName));

Document document = new Document(pdfDoc, new PageSize(one));

PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());

for (int i = 0; i < total; i++) {   

    canvas.circle(X[d * i + axisX], X[d * i + axisY], 1.0);
    canvas.fillStroke();
    // -- numbers (i+1) should be drawn beside the circles

}

如上所示,我如何使用上述 for 循环并在圆圈旁边写下数字?

【问题讨论】:

    标签: java pdf itext itext7


    【解决方案1】:

    使用 iText 7 在绝对位置添加文本有很多不同的方法。

    由于您已经有一个PdfCanvas 对象,您可以使用非常低级的方法,即逐行编写 PDF 语法:

    canvas.beginText();
    canvas.moveText(x, y);
    canvas.showText("1");
    canvas.endText();
    

    chapter 3 of the iText 7 jump-start tutorial 对此进行了解释。

    当您不熟悉 PDF 参考时,编写低级 PDF 语法很容易出错。还有一种更简单的方法:

    document.showTextAligned(new Paragraph("1"), x, y, TextAlignment.CENTER);
    

    现在您不必担心使用beginText() 和endText() 构造文本对象; iText 负责所有低级语法。

    chapter 2 of the building blocks tutorial 对此进行了解释。

    【讨论】:

    • 谢谢。我尝试了第一个建议,现在我有了“font.and.size.must.be.set.before.writing.any.text”异常。我试过“PdfFont font = PdfFontFactory.createFont(FONT, PdfEncodings.CP1250, true);”,但这会产生一堆错误。我将不胜感激。
    猜你喜欢
    • 2021-11-27
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    相关资源
    最近更新 更多