Text2PdfColumns.java(iText 5)

假設我們有以下文字檔案: jekyll_hyde.txt

我們如何將其轉換為如下所示的 PDF:

StackOverflow 文件

使用 iText 5 時,你需要這樣的程式碼:

public void createPdf(String dest)
throws DocumentException, IOException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    ColumnText ct = new ColumnText(writer.getDirectContent());
    BufferedReader br = new BufferedReader(new FileReader(TEXT));
    String line;
    Paragraph p;
    Font normal = new Font(FontFamily.TIMES_ROMAN, 12);
    Font bold = new Font(FontFamily.TIMES_ROMAN, 12, Font.BOLD);
    boolean title = true;
    while ((line = br.readLine()) != null) {
        p = new Paragraph(line, title ? bold : normal);
        p.setAlignment(Element.ALIGN_JUSTIFIED);
        title = line.isEmpty();
        ct.addElement(p);
    }
    Rectangle[] columns = {
        new Rectangle(36, 36, 290, 806), new Rectangle(305, 36, 559, 806)
    };
    int c = 0;
    int status = ColumnText.START_COLUMN;
    while (ColumnText.hasMoreText(status)) {
        ct.setSimpleColumn(columns[c]);
        status = ct.go();
        if (++c == 2) {
            document.newPage();
            c = 0;
        }
    }
    document.close();
}

資料來源: developers.itextpdf.com