1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > java pdf 转txt文件怎么打开_使用iText将TXT文件转换为PDF(保留格式)

java pdf 转txt文件怎么打开_使用iText将TXT文件转换为PDF(保留格式)

时间:2020-01-06 21:45:56

相关推荐

java pdf 转txt文件怎么打开_使用iText将TXT文件转换为PDF(保留格式)

我正在尝试使用iText库将.txt文件转换为.pdf文件。我面临的问题如下:

我在txt文件中有清晰的格式,与此类似:

TEXT *******************

Other text here * SOME_CODE_HERE_ *

Other text *******************

在输出中,格式消失了,看起来像这样:

TEXT ******************

Other text here * SOME_CODE_HERE_ *

Other text ******************

代码如下:

public static boolean convertTextToPDF(File file) throws Exception {

BufferedReader br = null;

try {

Document pdfDoc = new Document(PageSize.A4);

String output_file = file.getName().replace(".txt", ".pdf");

System.out.println("## writing to: " + output_file);

PdfWriter.getInstance(pdfDoc, new FileOutputStream(output_file)).setPdfVersion(PdfWriter.VERSION_1_7);;

pdfDoc.open();

Font myfont = new Font();

myfont.setStyle(Font.NORMAL);

myfont.setSize(11);

pdfDoc.add(new Paragraph("\n"));

if (file.exists()) {

br = new BufferedReader(new FileReader(file));

String strLine;

while ((strLine = br.readLine()) != null) {

Paragraph para = new Paragraph(strLine + "\n", myfont);

para.setAlignment(Element.ALIGN_JUSTIFIED);

pdfDoc.add(para);

}

} else {

System.out.println("no such file exists!");

return false;

}

pdfDoc.close();

}

catch (Exception e) {

e.printStackTrace();

} finally {

if (br != null)

br.close();

}

return true;

}

我还尝试使用IDENTITY_H创建BaseFont,但是它不起作用。我猜这是关于编码或类似的东西。你怎么看?我用完了解决方案…

谢谢

LE:正如艾伦(Alan)以及iText页面上的教程所建议的那样,除了我现有的代码外,我还使用了这一部分,并且效果很好。

BaseFont courier = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.EMBEDDED);

Font myfont = new Font(courier);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。