Text2Pdf.java(iText 5)

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

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

StackOverflow 文件

使用 iText 5 時,我們使用以下程式碼:

public void createPdf(String dest)
throws DocumentException, IOException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    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();
        document.add(p);
    }
    document.close();
}

資料來源: developers.itextpdf.com