サーチ…


備考

プレーンテキストファイルをPDFドキュメントに変換するコードは、iText 5またはiText 7を使用するかどうかにかかわらず非常に簡単です。iText 7では、ドキュメントのレベルでアライメントを定義できるという利点があります。 iText 5では、別々のParagraphオブジェクトごとに整列を設定する必要があります。

この2つの例のiText 5とiText 7の実際の違いを理解するためには、結果として得られるPDFを見直さなければなりません。 iText 5では、35ページのテキストで終わります。 iText 7では、同じテキストが38ページにわたって配布されています。

レイアウトを作成するときに異なるデフォルトが使用されるため、テキストはiText 7で作成すると読みやすくなります。あなたはiText 5のコードから同じ結果を得ることができますが、間隔に関していくつかの値を変更する必要があります。

iText 7では、iTextの16年の経験に基づいてデフォルト値が選択されました。このようにすれば、少ないコードでより良い結果を得ることができます。

もっと知りたい?

iText 7:ビルディングブロックチュートリアルの第5章であるRootElementの使用を読んでください。 無料の電子ブックを手に入れよう!

Text2Pdf.java(iText 5)

次のテキストファイルがあるとします。jekyll_hyde.txt

どうすればこのようなPDFに変換できますか?

ここに画像の説明を入力

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

Text2Pdf.java(iText 7)

次のテキストファイルがあるとします。jekyll_hyde.txt

どうすればこのようなPDFに変換できますか?

ここに画像の説明を入力

iText 7を使用する場合、次のコードが必要です。

public void createPdf(String dest) throws IOException {
    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    Document document = new Document(pdf)
        .setTextAlignment(TextAlignment.JUSTIFIED);
    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.comおよびiText 7:Building Blocksチュートリアル



Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow