我正在尝试使用 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,但它不起作用。 我想这是关于编码或类似的东西。 你怎么认为?我用完了解决方案...
谢谢
乐: 正如 Alan 和 iText 页面上的教程所建议的那样,除了我现有的代码之外,我还使用了这部分并且它工作正常。
BaseFont courier = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.EMBEDDED);
Font myfont = new Font(courier);
最佳答案
您需要使用等宽字体,例如 express 。
关于java - 使用 iText 将 TXT 文件转换为 PDF(保留格式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26925856/