我正在尝试使用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);
我正在尝试使用iText库将.txt文件转换为.pdf文件。我面临的问题如下:我在txt文件中有一个清晰的格式,与此类似:TEXT ...
您需要使用等宽字体,例如快递。
我知道这很旧,但是我在将文本文件转换为pdf时遇到了相同的问题,并且我使用了它(我在vb.net中写了这个:]