package com.inkasso.factoring.common.util.onlineConverter;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

import com.common.ajax.EncodingDetect;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

/**
 * @className:TextConverterPdfUtil
 * @description:文本文件.txt 转换成PDF
 * @author:杜小姣
 * @e-mail:1261237207@qq.com
 * @date:2018年7月9日 下午6:10:50
 */
public class TextConverterPdfUtil {

    private static TextConverterPdfUtil parser = null;

    private TextConverterPdfUtil(){
    }

    public static synchronized TextConverterPdfUtil getInstance() {
        if (parser == null) {
            parser = new TextConverterPdfUtil();
        }
        return parser;
    }

    @SuppressWarnings("unused")
    public void text2Pdf(String text, String pdf) {
        try {
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
            FileOutputStream out = new FileOutputStream(pdf);
            Rectangle rect = new Rectangle(PageSize.A4.rotate());
            Document doc = new Document(rect);
            PdfWriter writer = PdfWriter.getInstance(doc, out);
            doc.open();
            Paragraph p = new Paragraph();
            p.setFont(FontChinese);
            String fileEncode = EncodingDetect.getJavaEncode(text);
            InputStreamReader streamReader = new InputStreamReader(new FileInputStream(text), fileEncode);
            int ch = 0;
            while ((ch = streamReader.read()) != -1) {
                // System.out.print(ch);
                String line = (char) ch + "";
                p.add(line);
            }
            streamReader.close();
            doc.add(p);
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        java.io.File file = new java.io.File(TextConverterPdfUtil.class.getResource("/").getPath());
        String path = file.getParentFile().getPath();
        path = java.net.URLDecoder.decode(path, "UTF-8");
        String text = path + "/1.txt";
        String pdf = path + "/1.txt.pdf";
        TextConverterPdfUtil p = TextConverterPdfUtil.getInstance();
        p.text2Pdf(text, pdf);
    }
}
