TxT轉PDF可以直接使用IText就可以了,IText在pdf領域可以說暫時是最好的方案了。通過直接讀取txt文件,然後生成pdf,再添加文本就可以了。
1)使用IText實現轉換
原理:
使用IText創建pdf,添加文本。
優點:
速度快。
缺點:
具體實現:
public class Txt2PDF {
private static final String FONT = "C:\\Windows\\Fonts\\simhei.ttf";
public static void text2pdf(String text, String pdf) throws DocumentException, IOException {
Document document = new Document();
OutputStream os = new FileOutputStream(new File(pdf));
PdfWriter.getInstance(document, os);
document.open();
//方法一:使用Windows系統字體(TrueType)
BaseFont baseFont = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont);
InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(text)), "GBK");
BufferedReader bufferedReader = new BufferedReader(isr);
String str = "";
while ((str = bufferedReader.readLine()) != null) {
document.add(new Paragraph(str, font));
}
document.close();
}
public static void main(String[] args) throws Exception {
String PDFTIMEDIR = "F:/pdf/";
String text = PDFTIMEDIR + "1.txt";
String pdf = PDFTIMEDIR + "1.txt.pdf";
text2pdf(text, pdf);
}
}
效率分析
耗時:2264ms
耗時:2079ms
耗時:2137ms
耗時:2224ms