如何使用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示例 下一篇:无