说明:一个偶然的机会,坐在我前面的一个"坏"MM给我发一个叫“盘龙”的小说,从不看小说的我,一发而不可收;可是txt格式的小说的不仅仅字小不容易看,没法分章节;并且超3m以上,一般的记事本还打不开,真纠结呀;于是就想把txt转换成pdf来方便查看;其实想想对于我们程序员就是在边玩边学习呀,呵呵。
一、所依赖的库
iText-2.1.7.jar
iTextAsian.jar
jxl.jar
二、DEMO源码
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
/**
* 将从.txt中读到的内容写到pdf中。
* */
public class ReadCreatePdf {
private final static String READFILEPATH = "D:\\盘龙.txt"; //txt文件
private final static String WRITEFILEPATH = "D:\\盘龙.pdf"; //生成的pdf文件
public static void main(String[] args) throws DocumentException,
IOException {
Document document = new Document(PageSize.A4, 80, 80, 60, 30);
PdfWriter.getInstance(document, new FileOutputStream(WRITEFILEPATH));
document.open();
BaseFont bfChinese = BaseFont.createFont("STSong-Light",
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bfChinese, 18, Font.NORMAL);
Paragraph t = new Paragraph("oracle手册", FontChinese); //起一个别名,上班老板都不会发现,呵呵。
t.setAlignment(Element.ALIGN_CENTER);
t.setLeading(30.0f);
document.add(t);
FontChinese = new Font(bfChinese, 11, Font.NORMAL);
BufferedReader read = null;
try {
read = new BufferedReader(new FileReader(READFILEPATH));
String line = null;
while ((line = read.readLine()) != null) {
t = new Paragraph(line, FontChinese);
t.setAlignment(Element.ALIGN_LEFT);
t.setLeading(20.0f);
document.add(t);
}
} catch (Exception e) {
System.out.println("目标文件不存,或者不可读!");
e.printStackTrace();
} finally {
try {
read.close();
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("============执行成功!===========");
}
}