Convert TXT file to PDF using iText (keep formatti

2019-01-20 15:12发布

问题:

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

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          ******************

The code looks like this:

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;
}

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...

Thanks

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);

回答1:

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



标签: java pdf itext