java pdf 转txt文件_PDF技术(二)-Java实现Txt转PDF文件-Go语言中文社区

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);

}

}

效率分析

33209cdb04f226ee61e86c23592aa027.png

0ec06a95c834b5ee66672be7d9e8b401.png

0e70b77ecaa69c196c101e23c05ffda9.png

耗时:2264ms

耗时:2079ms

耗时:2137ms

耗时:2224ms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值