700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java pdf 转txt文件_java – 使用iText将TXT文件转换为PDF(保持格式化)

java pdf 转txt文件_java – 使用iText将TXT文件转换为PDF(保持格式化)

时间:2021-06-10 15:43:36

相关推荐

java pdf 转txt文件_java  – 使用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);

解决方法:

您需要使用等宽字体,例如信使.

标签:java,pdf,itext

来源: https://codeday.me/bug/0929/1832612.html

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