版权声明:本文为博主原创文章,转载添加原文链接 https://blog.csdn.net/qq_34190023/article/details/82999544
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