Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

java - Convert TXT file to PDF using iText (keep formatting)

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

        if (file.exists()) {

            br = new BufferedReader(new FileReader(file));
            String strLine;

            while ((strLine = br.readLine()) != null) {
                Paragraph para = new Paragraph(strLine + "
", 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...