0

how can i get this alignment on itext :

From this lines :

itext
I use java, itext to write pdf docs
java

Can i get this :

                        itext
                        I use java, itext to write pdf docs
                        java

The second line is centered.

4

2 回答 2

0

使用 iText 获得您想要的东西并不容易,但这可能是一种可行的方法。您可以创建一个 1 行 3 列的表格,并将您的文本放在中间列中,并带有ALIGN_LEFT. 此解决方案的唯一问题是 iText 中的列宽必须手动设置,因此您必须在运行时计算中间单元格所需的宽度以获得所需的输出。

这里有一个例子:

String[] rows = {"line 1", "line 222222222222222222", "line 3", "line 4 QWERTOPASDFVBNM"};

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("C:/SimplePDF.pdf"));
document.open();

document.newPage();

// Creating PdfPTable with 3 cell [Empty][Your Test][Empty]
PdfPTable table = new PdfPTable(3);
PdfPCell fake = new PdfPCell();

fake.setBorder(Rectangle.NO_BORDER); // Hiding Border
table.addCell(fake);

// Creating middle cell
PdfPCell c = new PdfPCell();
c.setHorizontalAlignment(Element.ALIGN_LEFT);
c.setBorder(Rectangle.NO_BORDER);

// Adding strings to the middle cell
for (String string : rows) {
    c.addElement(new Paragraph(string));
}

table.addCell(c);

table.addCell(fake);

// Setting manually column widths
// Depending on String length added before, you should get the
// max length string and compute the width for the middle cell, 
// then the others 2 are just (100% - middle_cell_width)/2
float[] columnWidths = {30f, 40f, 30f};
table.setWidths(columnWidths);

document.add(table);
document.close();

这里将如何显示:

输出截图

于 2013-08-28T08:23:09.017 回答
0

您可以在 itext 中设置选项卡设置,请参考此链接itext-tab

此代码将起作用,您可以自定义标签宽度

public class TabSpacing {

    public static final String DEST = "/home/sunil/Desktop/tab.pdf";

    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new TabSpacing().createPdf(DEST);
    }

    public void createPdf(String dest) throws FileNotFoundException, DocumentException {
        Document document = new Document();

        PdfWriter.getInstance(document, new FileOutputStream(dest));

        document.open();

        Paragraph p = new Paragraph();
        p.setTabSettings(new TabSettings(200f));
        p.add(Chunk.TABBING);
        p.add(new Chunk("itext"));
        document.add(p);

        p = new Paragraph();
        p.setTabSettings(new TabSettings(200f));
        p.add(Chunk.TABBING);
        p.add(new Chunk("I use java, itext to write pdf docs"));

        document.add(p);

        p = new Paragraph();
        p.setTabSettings(new TabSettings(200f));
        p.add(Chunk.TABBING);
        p.add(new Chunk("java"));
        document.add(p);

        document.close();
    }

} 
于 2018-10-21T20:13:38.593 回答