如何使用Java格式化PDF中的文本?

如何使用Java格式化PDF中的文本?

注:iText開發環境設置,下載iText7 jar(社區版:http://github.com/itext/itext7/releases/tag/7.0.4 ) ,創建一個工程:java_itext,並將下載的itext7 jar包和slf4j( http://www.slf4j.org/download.html )工具包添加到構建路徑中。專案結構如下圖所示 -

以下是使用Java格式化PDF中的文本的程式。

package com.zaixian;

import com.itextpdf.io.font.FontConstants;

import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;

import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;

public class FormatTextInPdf {
    public static void main(String args[]) throws Exception {
        String file = "formatingTextInPDF2.pdf";

        // Creating a PdfDocument object
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));

        // Creating a Document object
        Document doc = new Document(pdfDoc);
        // 中文支持
        PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", false);
        // Adding text to the document
        Text text1 = new Text(
                "許虎虎是因特網上最大的 IT技術學習和開發者資源網站。包括全面的教學、完善的參考手冊以及龐大的代碼庫。" + "" + "許虎虎每月接受成千上萬的用戶訪問,並產生幾十萬以上的頁面流覽量。");

        // Setting color to the text
        text1.setFontColor(Color.RED);

        // Setting font to the text
        text1.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA));
        text1.setFont(font);

        // Creating a paragraph 1
        Paragraph para1 = new Paragraph(text1);

        Text text2 = new Text("許虎虎把提供高品質的 IT技術學習入門實例教學資源作為自身的使命。" + ""
                + "許虎虎將為用戶提供永久免費的內容和服務。許虎虎運行費用主要來自兩方面:少量的捐款及廣告收入。" + "" + "許虎虎一直將全部資金用於網站內容的開發以及伺服器硬體的升級和維護。");

        // Setting color to the text
        text2.setFontColor(Color.RED);

        // Setting font to the text
        text2.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA));
        text2.setFont(font);

        // Creating a paragraph 2
        Paragraph para2 = new Paragraph(text2);

        // Adding paragraphs to the document
        doc.add(para1);
        doc.add(para2);

        // Closing the document
        doc.close();
        System.out.println("Text format successfully...");
    }
}

執行上面示例代碼,得到以下結果 -

Text format successfully...

輸出檔內容如下所示 -


上一篇: Java iText示例 下一篇:無