【发布时间】:2015-01-11 14:24:33
【问题描述】:
我正在尝试使用 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);
【问题讨论】: