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