如何将iText LIST放在具有特定字体和对齐的绝对位置?

时间:2018-06-10 12:55:01

标签: java itext

public void printTextOnAbsolutePosition(String teks, PdfWriter writer, Rectangle rectangle, boolean useAscender) throws Exception {
    Font fontParagraf = new Font(Font.FontFamily.HELVETICA, 10, Font.NORMAL);
    rectangle.setBorder(Rectangle.BOX);
    rectangle.setBorderColor(BaseColor.RED);
    rectangle.setBorderWidth(0.0f);
    PdfContentByte cb = writer.getDirectContent();
    cb.rectangle(rectangle);

    Paragraph para = new Paragraph(teks, fontParagraf);
    ColumnText columnText = new ColumnText(cb);
    columnText.setSimpleColumn(rectangle);
    columnText.setUseAscender(useAscender);
    columnText.addText(para);

    columnText.setAlignment(3);
    columnText.setLeading(10);
    columnText.go();
}

我们可以使用上面的代码在绝对位置打印带有iText的文本。但是我们如何才能与List实现相同的目标呢?另外,如何格式化列表的文本,以便它使用某些字体和文本对齐?

1 个答案:

答案 0 :(得分:0)

public void putBulletOnAbsolutePosition(String yourText, PdfWriter writer, Float koorX, Float koorY, Float lebarX, Float lebarY) throws Exception {
    List listToBeShown = createListWithBulletImageAndFormatedFont(yourText);

    // ... (the same) ...

    columnText.addElement(listToBeShown);
    columnText.go();
}

该方法基本相同。通过查看文档,我们发现不使用ColumnText上的.addtext,而是使用接受Paragraph,List,PdfPTable和Image的.addElement

至于格式化列表文本,我们只需要将paragraf作为列表的输入(而不是使用columnText.setAlignment()来设置对齐)。

public List createListWithBulletImageAndFormatedFont(String yourText) throws Exception {
    Image bulletImage = Image.getInstance("src/main/resources/japoimages/bullet_blue_japo.gif");
    bulletImage.scaleAbsolute(10, 8);
    bulletImage.setScaleToFitHeight(false);

    List myList = new List();
    myList.setListSymbol(new Chunk(Image.getInstance(bulletImage), 0, 0));

    String[] yourListContent = yourText.split("__");
    Font fontList = new Font(Font.FontFamily.HELVETICA, 10, Font.NORMAL);

    for (int i=0; i < yourListContent.length; i++) {
        Paragraph para = new Paragraph(yourListContent[i], fontList);
        para.setAlignment(Element.ALIGN_JUSTIFIED);
        myList.add(new ListItem(para));
    }
    return myList;
}

以上代码将在我们想要的任何位置打印项目符号列表(使用图像)。

public void putBulletnAbsolutePosition (String dest) throws Exception {
    Document document = new Document(PageSize.A5, 30,30, 60, 40);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();

    String myText = "ONE__TWO__THREE__FOUR";
    putBulletOnAbsolutePosition(myText, writer, 140f, 350f, 300f, 200f);

    document.close();
}