Java language implements the conversion of Text format to pdf file

 The folder can be downloaded and imported in the attachment.

 

import java.io.BufferedReader;     

import java.io.FileOutputStream;     

import java.io.FileReader;     

import java.io.IOException;     

import com.lowagie.text.Document;     

import com.lowagie.text.DocumentException;     

import com.lowagie.text.Element;     

import com.lowagie.text.Font;     

import com.lowagie.text.PageSize;     

import com.lowagie.text.Paragraph;     

import com.lowagie.text.pdf.BaseFont;     

import com.lowagie.text.pdf.PdfWriter;     

  

/**   

 * Write the content read from .txt to pdf.   

 * */    

public class GeneratePDF {     

    private final static String READFILEPATH = "E:\\2.txt";  //txt文件     

    private final static String WRITEFILEPATH = "E:\\2.pdf"; //The generated pdf file     

    

    public static void main(String[] args) throws DocumentException,     

            IOException {     

        Document document = new Document(PageSize.A4, 80, 80, 60, 30);     

        PdfWriter.getInstance(document, new FileOutputStream(WRITEFILEPATH));     

        document.open();     

        BaseFont bfChinese = BaseFont.createFont("STSong-Light",     

                "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);     

        Font FontChinese = new Font(bfChinese, 18, Font.NORMAL);     

        Paragraph t = new Paragraph("convert text to pdf", FontChinese); 

        t.setAlignment(Element.ALIGN_CENTER);     

        t.setLeading(30.0f);     

        document.add(t);     

        FontChinese = new Font(bfChinese, 11, Font.NORMAL);     

        BufferedReader read = null;     

        try {     

            read = new BufferedReader(new FileReader(READFILEPATH));     

            String line = null;     

            while ((line = read.readLine()) != null) {     

                t = new Paragraph(line, FontChinese);     

                t.setAlignment(Element.ALIGN_LEFT);     

                t.setLeading(20.0f);     

                document.add(t);     

            }     

        } catch (Exception e) {     

            System.out.println("The target file does not exist, or is not readable!");     

            e.printStackTrace ();     

        } finally {     

            try {     

                read.close();     

                document.close();     

            } catch (IOException e) {     

                e.printStackTrace ();     

            }     

        }     

        System.out.println("============Build Success!===========");     

    }     

}    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326399920&siteId=291194637