今天学习iText,写了个Java小工程练了下手。
我的电脑操作系统版本为Win7旗舰版(ServicePack1),jdk版本为1.8
程序使用的jar包有:
1、iText-5.0.6.jar,下载地址:http://download.youkuaiyun.com/download/huiqi110/4468301
2、itextasian-1.5.2.jar,下载地址:http://cn.jarfire.org/itextasian.html
如要下载最新版本iText5.5.9,下载地址:https://github.com/itext/itextpdf/releases/tag/5.5.9
上面两个jar包中, iText-5.0.6.jar是iText的基本包,itextasian-1.5.2.jar用于支持iText对中文的显示。
直接下载的itextasian-1.5.2.jar可能会导致程序报错:
com.itextpdf.text.DocumentException: Font 'STSong-Light' with 'UniGB-UCS2-H' is not recognized.
此时处理办法是用WinRAR打开 itextasian-1.5.2.jar,将其中路径com/lowagie/text/pdf/fonts/中的lowagie改为itextpdf即可
现有txt文件“《三国演义》篇尾诗.txt”,内容如下:
《三国演义》篇尾诗
[明]罗贯中
高祖提剑入咸阳,炎炎红日升扶桑;光武龙兴成大统,金乌飞上天中央;
哀哉献帝绍海宇,红轮西坠咸池傍!何进无谋中贵乱,凉州董卓居朝堂;
王允定计诛逆党,李傕郭汜兴刀枪;四方盗贼如蚁聚,六合奸雄皆鹰扬;
孙坚孙策起江左,袁绍袁术兴河梁;刘焉父子据巴蜀,刘表军旅屯荆襄;
张燕张鲁霸南郑,马腾韩遂守西凉;陶谦张绣公孙瓒,各逞雄才占一方。
曹操专权居相府,牢笼英俊用文武;威挟天子令诸侯,总领貌貅镇中土。
楼桑玄德本皇孙,义结关张愿扶主;东西奔走恨无家,将寡兵微作羁旅;
南阳三顾情何深,卧龙一见分寰宇;先取荆州后取川,霸业图王在天府;
呜呼三载逝升遐,白帝托孤堪痛楚!孔明六出祁山前,愿以只手将天补;
何期历数到此终,长星半夜落山坞!姜维独凭气力高,九伐中原空劬劳;
钟会邓艾分兵进,汉室江山尽属曹。丕睿芳髦才及奂,司马又将天下交;
受禅台前云雾起,石头城下无波涛;陈留归命与安乐,王侯公爵从根苗。
纷纷世事无穷尽,天数茫茫不可逃。鼎足三分已成梦,后人凭吊空牢骚。
java代码如下:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
public class GenPdfByIText {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream("D:\\output.pdf"));
//创建一个简体中文的基本字体、UniGB-UCS2-H为简体中文
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED);
Font fontChinese = new Font(base, 16, Font.NORMAL);
document.open();
try {
StringBuilder buffer = new StringBuilder();
InputStream is = new FileInputStream("C:/Users/Tsybius/Desktop/《三国演义》篇尾诗.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = reader.readLine().substring(1); //去除最前面的\udbff\udeff
document.add(new Paragraph(line, fontChinese));
while (line != null) {
buffer.append(line);
buffer.append("\n");
line = reader.readLine();
document.add(new Paragraph(line, fontChinese));
}
reader.close();
is.close();
} catch (Exception ex) {
throw ex;
}
} catch (Exception ex) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
ex.printStackTrace(printWriter);
System.out.println(stringWriter.toString());
} finally{
document.close();
}
System.out.println("DONE.");
}
}
运行结果为,在D盘生成了output.pdf文件,效果如下:
END