gistfile1.txt package freemarker.hiveview.com;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.Writer;i
package freemarker.hiveview.com; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer; import com.itextpdf.text.pdf.BaseFont; import freemarker.template.Configuration; import freemarker.template.Template; public class TestDemo { public static void main(String[] args) { getPdf(); } public static void getPdf(){ Mapmap = new HashMap (); map.put("subname", "dhc"); map.put("orderId", 12); map.put("sumFee", "aa"); map.put("payUrl", "bb"); map.put("subNumber", "cc"); map.put("opName", "dd"); map.put("date","ee"); Configuration conf = new Configuration(); try { conf.setDirectoryForTemplateLoading(new File("./ftl")); conf.setDefaultEncoding("UTF-8"); Template template = conf.getTemplate("dhc.ftl"); System.out.println(template); //將模板轉換成html文件 //C:\Users\hewe\Documents\data String htmlFilePath = "C:/Users/hewe/Documents/data/demo/dhc.html"; File file = new File(htmlFilePath); if(!file.exists()){ file.createNewFile(); } Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file),"UTF-8")); template.process(map, writer); writer.flush(); //將html文件轉換為pdf文件,并保存在本地 String url = new File(htmlFilePath).toURI().toURL().toString(); String pdfFilePath = "C:/Users/hewe/Documents/data/demo/dhc.pdf"; OutputStream ops = new FileOutputStream(new File(pdfFilePath)); ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(url); //解決亂碼 問題 ITextFontResolver fontResolver = renderer.getFontResolver(); fontResolver.addFont("C:/Users/hewe/Documents/simsun.ttc", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);; renderer.layout(); renderer.createPDF(ops); System.out.println("ok"); } catch (Exception e) { e.printStackTrace(); } } }