Apache PDFBox: How can I specify the position of the texts I'm outputting

戏子无情 提交于 2019-12-02 09:34:23

In your code you already choose the position for the first line start like this:

contentStream.newLineAtOffset(175, 670);

Concerning your question

how do I do it for text that are located on different positions

therefore: You simply use newLineAtOffset again!

You have to be aware, though, that newLineAtOffset(x, y) does not set the new line start to the absolute coordinates x, y but instead adds these values to the coordinates of the previous line start, hence the AtOffset in the method name.

As the previous line start coordinates are reset to 0, 0 at the start of a text object (contentStream.beginText()), your first newLineAtOffset in a text object appears to use absolute coordinates.

So if you prefer to use absolute coordinates, you can start a new text object each time you need to move the line start differently than contentStream.newLine() does.

If you are ok with relative coordinates, though, you don't need to start new text objects that often but instead use offsets from line start to line start in newLineAtOffset, e.g.:

try (PDDocument document = new PDDocument()) {
    PDPage page = new PDPage();
    document.addPage(page);

    PDFont font = PDType1Font.HELVETICA;

    String text = "Text 1";
    String text1 = "Text 2";
    String text2 = "Text 3";
    String text3 = "Text 4";
    String text4 = "Text 5";
    String text5 = "Text 6";

    try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
        contentStream.beginText();

        contentStream.newLineAtOffset(175, 670);
        contentStream.setFont(font, 12);
        contentStream.setLeading(15);
        contentStream.showText(text);
        contentStream.newLine();
        contentStream.showText(text1);      

        contentStream.newLineAtOffset(225, 10);
        contentStream.setFont(font, 15);
        contentStream.showText(text2);      

        contentStream.newLineAtOffset(-390, -175);
        contentStream.setFont(font, 13.5f);
        contentStream.setLeading(17);
        contentStream.showText(text3);
        contentStream.newLine();
        contentStream.showText(text5);      

        contentStream.newLineAtOffset(300, 13.5f);
        contentStream.showText(text4);      

        contentStream.endText();

        contentStream.moveTo(0, 520);
        contentStream.lineTo(612, 520);
        contentStream.stroke();
    }

    document.save(TARGET_FILE);
}

(ArrangeText test testArrangeTextForTeamotea)

which results in

which in turn approximates your image. (I have not counted pixels in your image, so this only is an approximation.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!