2013年5月24日 星期五

使用Flying Saucer 將html內容產生PDF

package flyingsaucerpdf;
   
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.pdf.BaseFont;

public class Chinexe {

    public static void main(String[] args) throws Exception {
        String _package = Chinexe.class.getPackage().getName();
        // 取得bin的路徑. ex: file/C:/
        String _rootDir = Chinexe.class.getResource("/").toString();
        String resPath = _package.replaceAll("\\.","/")+"/../resources/";
       
        StringBuffer html = new StringBuffer();
        //组装成符合W3C标准的html文件,否则不能正确解析
        html.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        html.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">")
        .append("<head>")
        .append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />")
        .append("<style type=\"text/css\" mce_bogus=\"1\">body {font-family: SimSun;}</style>")
        .append("<style type=\"text/css\">img {width: 700px;}</style>")
        .append("</head>")
        .append("<body>");
       
        html.append("<center><h1>統計</h1></center>");
        html.append("<center>");
        html.append("<img src=\"images/chart.jpg\"/>");
        html.append("</center>");
       
        html.append("</body></html>");
       
        // parse our markup into an xml Document
        try {
            ITextRenderer renderer = new ITextRenderer();
            /**
             * 引入了新的jar包,不用再导入字体了
             */
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(resPath + "simsun.ttc",
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
           
            renderer.setDocumentFromString(html.toString());
            renderer.getSharedContext().setBaseURL(_rootDir + "resources/" );
           
            String outputFile = "100bottles.pdf";
            OutputStream os = new FileOutputStream(outputFile);
            renderer.layout();
            renderer.createPDF(os);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

沒有留言: