Text2PdfColumns.java(iText 7)

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

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

StackOverflow 文件

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

public void createPdf(String dest) throws IOException {
    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    Document document = new Document(pdf)
        .setTextAlignment(TextAlignment.JUSTIFIED);
    Rectangle[] columns = {
        new Rectangle(36, 36, 254, 770),
        new Rectangle(305, 36, 254, 770)};
    document.setRenderer(new ColumnDocumentRenderer(document, columns));
    BufferedReader br = new BufferedReader(new FileReader(TEXT));
    String line;
    PdfFont normal = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
    PdfFont bold = PdfFontFactory.createFont(FontConstants.TIMES_BOLD);
    boolean title = true;
    while ((line = br.readLine()) != null) {
        document.add(new Paragraph(line).setFont(title ? bold : normal));
        title = line.isEmpty();
    }
    document.close();
}

資料來源: developers.itextpdf.comiText 7:Building Blocks 教程。