以eclispse为开发平台
引用的jar包 :
First:
在项目JSP中开启下载的方法
/*
* 生成pdf浏览页面
*/
function downLoadToPDF(taskId){
var rootpath=BaseContext+"/DemoController/download?TaskId="+taskId;//访问路径
window.open(rootpath, "_blank");//新开界面
}
接着进入这个DemoController
/*生成PDF的后台代码
*/
public class TestPDFUtil {
public static void main(String[] args) {
String templateName = "template";//需要选用的模板名称
String targetPathRoot = "D:/temp/";//生成pdf的目标位置
Map<String, Object> map = generateUnitOpenAccountApplicationData();//构建模板所需数据,根据自己需求去整
try {
String path = PDFUtil.getPath();//首先获取项目路径 调用工具类中的方法
PDFUtil.generateToFile(path,"......./" + templateName + ".ftl", path + "/images/", map, targetPathRoot + templateName + ".pdf");//路径 ==》根据自己项目中的template文件
System.out.println("生成PDF成功!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("生成PDF失败!");
}
}
接着是辅助工具类:
package util.PDFUtil;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.Locale;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
@SuppressWarnings("all")
public class PDFUtil {private static final Logger logger = LoggerFactory.getLogger(PDFUtil.class);
public static void generateToFile(String ftlPath,String fileName,String imageDisPath,Object data,String outputFile) throws Exception{
OutputStream out=null;
ITextRenderer render =null;
try{
String html=getPdfContent(ftlPath,ftlName,data);
out =new FileOutputStream(outputFile);
render =getRender();
render.setDocumentFromString(html);
if(imageDiskPath != null && !imageDispath.equals("")){
//若html中有图片时进入,图片的路径使用项目的绝对路径这个是作为根路径
render.getSharedContext().setBaseURL("file:/"+iamgeDisPath);
}
render.layerout();
render.createPDF();
render.finishPDF();
render=null;
return out;
}catch(Exception e){
logger.error("Exception:",e);
throw e;}finally{
if (out != null) {
try {
out.close();
} catch (IOException e) {
logger.error("Exception:",e);
throw e;
}
}
}}
//获取PDF的内容
public static String getPdfContent(String ftlPath,String ftlName,Object o) throws Exception {
return userTemplate(ftlPath,ftlName,o);
}
//使用freeMake得到html内容
public static String useTemplate(String ftlPath,String ftlName,Object o)throws Exception {
String html =null;
Template tpl=getFreemakerConfig(ftlPath).getTemplate(ftlName);
tpl.setEcncoding("UTF-8");
StringWriter writer =newStringWriter();
tpl.process(o,writer);
writer.flush();
html=writer.toString();
return html;
}
//获取freemarker配置
private static Configutation getFreemarkerConfig(String templatePath)throws IOException{
Configuration config=new Configuration();
config.setDirectoryForTemplateLoading(new File(templatePath));
config.setEncoding(Locale.CHINA,"utf-8");
return config;
}
public static ITextRenderer getRender() throws() DocumentException,IOException{
ITextRenderer render =new ITextRender();
String path =getPath();
//添加字体 以支持中文 字体文件路径要找对
render.getFontResolver().addFont(path+"../fonts/ARIALUNI.TTF",BaseFont,IDENTITY_H,BaseFont.NOT_EMBEDDED);
render.getFontResolver().addFont(path+"../fonts/SIMSUNB.TTF",BaseFont,IDENTITY_H,BaseFont.NOT_EMBEDDED);
return render;
}
//获取项目根路径
public static String getPath(){
//return PDFUtil.class.getResource("").getPath().substring(1)://返回类路径(当前类所在的路径)
//return PDFUtil.class.getResource("/").getPath().substring(1);//返回根路径(编译之后的根路径)
return PDFUtil.class.getClassLoader().getResource("").getPath();
}
}
工具类中为所需要的一些方法,对于路径问题一定要看清楚,否则会访问不到数据,所以在调试的时候一定要打断点进行调整,找到符合自己的项目路径。
然后是存放数据,用map集合来存放
/**
* 添加页面所需要的各种参数
* @param patient
* @param task
* @param mettTask
* @param request
* @return
*/
private Map generateUnitOpenAccountApplicationData(Patient patient,
Task task, List<MettTask> mettTask,List<ScaleTask> scaleTask,
HttpServletRequest request,List<CemtTask> cemtTask) {
Map<String, Object> total_map = new HashMap<String, Object>();//存放总体数据
Map<String, Object> map = new HashMap<String, Object>();//存放总体数据
map=Word_stage_Util.createModel(patient,task); //获取数据并整合,此为要存放数据进行数据库读写之后进行选择判断
total_map.put("data", map);//总体存放
return total_map;
}
下载模板的html界面展示
ftl内部预览:
字体需求:
***本技术由LHF支持,稍后会上传jar包和字体