package com.phbc.spark.utils;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.pdf.BaseFont;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class PDFUtil {
/**
* pdf文档导出
* @param request
* @param ftlName 文件名
* @param root 导出数据
* @return
* @throws Exception
*/
public static ByteArrayOutputStream createPDF(HttpServletRequest request, String ftlName,Map root) throws Exception {
String basePath =request.getSession().getServletContext().getRealPath("/");//绝对路径
Configuration cfg = new Configuration();
try {
cfg.setLocale(Locale.CHINA);
cfg.setEncoding(Locale.CHINA, "UTF-8");
//设置编码
cfg.setDefaultEncoding("UTF-8");
//设置模板路径
cfg.setDirectoryForTemplateLoading(new File(basePath + "/WEB-INF/template"));
//获取模板
Template template = cfg.getTemplate(ftlName);
template.setEncoding("UTF-8");
Writer writer = new StringWriter();
//数据填充模板
template.process(root, writer);
String str = writer.toString();
//pdf生成
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
ITextRenderer iTextRenderer = new ITextRenderer();
iTextRenderer.setDocumentFromString(str);
//设置字体 其他字体需要添加字体库
ITextFontResolver fontResolver = iTextRenderer.getFontResolver();
fontResolver.addFont(basePath + "/WEB-INF/template/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// System.out.println(basePath);
// System.out.println(str);
iTextRenderer.setDocument(builder.parse(new ByteArrayInputStream(str.getBytes("utf-8"))),null);
iTextRenderer.layout();
//生成PDF
ByteArrayOutputStream baos = new ByteArrayOutputStream();
iTextRenderer.createPDF(baos);
baos.close();
return baos;
} catch(Exception e) {
throw new Exception(e);
}
}
/**
* 客户端下载pdf
* @author
* 创建时间
* @param response
* @param bytes
* @param filename
*/
public static void renderPdf(HttpServletResponse response, final byte[] bytes, final String filename) {
/* initResponseHeader(response, PDF_TYPE); */
setFileDownloadHeader(response, filename, ".pdf");
if (null != bytes) {
try {
response.getOutputStream().write(bytes);
response.getOutputStream().flush();
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}
/**
* 分析并设置contentType与headers.
*/
/*
private HttpServletResponse initResponseHeader(HttpServletResponse response, final String contentType, final String... headers) {
// 分析headers参数
String encoding = DEFAULT_ENCODING;
boolean noCache = DEFAULT_NOCACHE;
for (String header : headers) {
String headerName = StringUtils.substringBefore(header, ":");
String headerValue = StringUtils.substringAfter(header, ":");
if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
encoding = headerValue;
} else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
noCache = Boolean.parseBoolean(headerValue);
} else {
throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
}
}
// 设置headers参数
String fullContentType = contentType + ";charset=" + encoding;
response.setContentType(fullContentType);
if (noCache) {
// Http 1.0 header
response.setDateHeader("Expires", 0);
response.addHeader("Pragma", "no-cache");
// Http 1.1 header
response.setHeader("Cache-Control", "no-cache");
}
return response;
} */
/**
* 设置让浏览器弹出下载对话框的Header
* @author
* 创建时间
* @param response
* @param fileName
* @param fileType
*/
public static void setFileDownloadHeader(HttpServletResponse response, String fileName, String fileType) {
try {
// 中文文件名支持
String encodedfileName = new String(fileName.getBytes("GBK"), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + fileType + "\"");
} catch (UnsupportedEncodingException e) {
}
}
}