首页 > 解决方案 > 如何将 iText LIST 放在具有特定字体和对齐方式的绝对位置上?

问题描述

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 实现同样的效果呢?另外,如何格式化列表的文本,使其使用特定的字体和文本对齐方式?

标签: javaitext

解决方案


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();
}

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

至于格式化列表文本,我们只需要将 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();
}

推荐阅读