一、文本或HTML生成PDF文檔
package com.pdftest; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.tool.xml.XMLWorkerHelper; public class CrePdf { public static void main(String[] args) throws IOException,DocumentException { // String HTML=creHtml(htmlStr); Date date = new Date(); DateFormat sdf=new SimpleDateFormat("MMddHHmmss"); String stime=sdf.format(date);//用於生成文件名 String filePdfPath="E:/abcd/Pdf"+stime+".pdf";//生成PDF文件的路徑 String HTML="E:/abcd/reportHtml.html";//HTML文件路徑 /*String imgPath1="file:/"+"E:/abcd/Koala.jpg"; Image img1=Image.getInstance(imgPath1); img1.scaleAbsolute(100, 100); img1.setAbsolutePosition(40, 310);*/ Document document=new Document(); PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(filePdfPath)); document.open(); /*document.add(img1);*/ XMLWorkerHelper.getInstance().parseXHtml(writer,document, new FileInputStream(HTML),null,new AsianFontProvider()); document.close(); System.out.println("輸出:E:/abcd/Result"+stime+".pdf"); } //如果是文本,先生成Html文件,再轉爲PDF private static String creHtml(String strContext){ String strs=strContext; Date date = new Date(); DateFormat sdf=new SimpleDateFormat("MMddHHmmss"); String stime=sdf.format(date); String fileResPath="E:/abcd/Html"+stime+".html"; File filew=new File(fileResPath); try{ FileWriter fw = new FileWriter(filew,true); BufferedWriter bufw=new BufferedWriter(fw); bufw.write(strs); bufw.close(); fw.close(); } catch(Exception e){ e.printStackTrace(); } return fileResPath; } }
itextpdf對中文支持有問題,需要寫一個處理方法
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
public class AsianFontProvider extends XMLWorkerFontProvider {
public Font getFont(final String fontname,final String encoding,
final boolean embedded,final float size,final int style,
final BaseColor color){
BaseFont bf=null;
try{
bf=BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
}catch(Exception e){
e.printStackTrace();
}
Font font=new Font(bf,size,style,color);
font.setColor(color);
return font;
}
}
注:如果包含圖片,部分html中src路徑可用。如存在問題,可用代碼中註釋的部分解決。getInstance爲文件路徑方法,scaleAbsolute爲圖片大小方法,setAbsolutePosition爲插入圖片位置的方法,可自己多調幾次到合適的位置。
二、FreeMarker模板+itextpdf
freeMarker的使用與Jsp有些類似。
public String freeMarkUtil(RiskControlApproveBean bean) throws IOException, TemplateException, DocumentException{
//文件名
Date date = new Date();
DateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSS");
DateFormat sdf24=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String stime24=sdf24.format(date);
int rad=(int) ((Math.random()*9+1)*100);
String stime=sdf.format(date)+rad;
Configuration conf=new Configuration();
String dir="E:/abcd/ftl";
String eDir="E:/abcd/";
conf.setDirectoryForTemplateLoading(new File(dir));
Template template=conf.getTemplate("examplePage.html");
Writer out=new FileWriter(new File(eDir+stime+".html"));
Map<String,Object> root=new HashMap<String,Object>();
//插入模板的Bean
CusInfoBean cusInfoBean = dao.getCusBaseInfo(bean);
root.put("cusInfoBean",cusInfoBean);
template.process(root, out);
out.flush();
out.close();
crePdf(stime);
jsonResponse.setSuccess(stime);
return null;
}
public static void crePdf(String htmlFileStr) throws IOException,DocumentException{
String HTML="E:/abcd/"+htmlFileStr+".html";
String filePdfPath="E:/abcd/"+htmlFileStr+".pdf";
Document document=new Document();
PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(filePdfPath));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer,document,new FileInputStream(HTML),null,new AsianFontProvider());
document.close();
System.out.println("輸出:"+filePdfPath);
}
Html模板:
<tr>
<td>姓名</td>
<td>${cusInfoBean.name}</td>
<td>性別</td>
<td>${cusInfoBean.sex}</td>
</tr>