使用iText将TXT文件转换为PDF(保持格式化) [英] Convert TXT file to PDF using iText (keep formatting)

查看:1172
本文介绍了使用iText将TXT文件转换为PDF(保持格式化)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to convert a .txt file into a .pdf file using iText library. The problem that I am facing is the following:

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

I have a clear formatting in the txt file, something similar with this:

TEXT                                   *******************
Other text here                        * SOME_CODE_HERE_ *
Other text                             *******************

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

And in the output the formatting is gone and looks like this:

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,但它不起作用。
我想这是关于编码或类似的东西。
您怎么看?我的解决方案用完了......

I also tried to create a BaseFont with IDENTITY_H but it doesn't work. I guess it's about the encoding or something like that. What do you think? I run out of solutions...

谢谢

LE:
正如Alan所说,通过iText页面的教程,我在现有代码中使用了这一部分并且工作正常。

LE: As suggested by Alan, and by the tutorial from iText's page, I used this part in addition with my existing code and it works fine.

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


推荐答案

您需要使用等宽字体,例如Courier。

You need to use a Monospaced Font e.g. Courier.

http://en.wikipedia.org/wiki/Monospaced_font

http://itextpdf.com /examples/iia.php?id=208

这篇关于使用iText将TXT文件转换为PDF(保持格式化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆