簡體   English   中英

使用itext的特殊對齊

[英]Special alignment using itext

我如何在itext上獲得此對齊方式:

從這行:

itext
I use java, itext to write pdf docs
java

我能得到這個嗎?

                        itext
                        I use java, itext to write pdf docs
                        java

第二行居中。

使用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();

這里將如何顯示它:

輸出截圖

您可以在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();
    }

} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM