所需要的主要的jar包
com.sun.mail javax.mail1.6.2 org.freemarker freemarker2.3.28 org.xhtmlrenderer flying-saucer-pdf9.1.16 com.itextpdf itextpdf5.5.13 com.lowagie itext2.0.8
主要java代码
TestController
@GetMapping(value = "/download")
public ResponseEntity> download(HttpServletResponse response) {
//文件路径
return testPdfBiz.download(response);
}
TestPdfBiz
@Slf4j
@Service
public class TestPdfBiz {
@Autowired
TestPdfService testPdfService;
public ResponseEntity> download(HttpServletResponse response) {
//文件路径
HttpHeaders headers = new HttpHeaders();
try {
byte[] pdfBytes = testPdfService.testPdf();
if (pdfBytes != null && pdfBytes.length > 0) {
String fileName = UUID.randomUUID() + ".pdf";
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity(pdfBytes, headers, HttpStatus.OK);
}
} catch (Exception e) {
e.printStackTrace();
}
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
return new ResponseEntity("{ "code" : "404", "message" : "not found" }",
headers, HttpStatus.NOT_FOUND);
}
}
TestPdfServiceImpl
@Override
public byte[] testPdf() {
Map dataMap = new HashMap<>(16);
dataMap.put("orderCode","2222");
dataMap.put("productPrice","100");
dataMap.put("userName","恒果果");
String ftlurl = "templates/website/pz/pz.ftl";
String ttcurl = "templates/website/fonts/simsun.ttc";
ClassPathResource res = new ClassPathResource(ftlurl);
InputStream in = null;
try {
in = res.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
// 把 InputStream 转换成字符串。CharStreams 来自 guava 库
try {
String emailBodyTemplate = CharStreams.toString(new InputStreamReader(
in, Charsets.UTF_8));
log.info("emailBodyTemplate {}",emailBodyTemplate);
} catch (IOException e) {
e.printStackTrace();
}
String htmlStr = PDFUtil.freemarkerRender(dataMap, ftlurl,PROFILES_ACTIVE);
log.info("htmlStr {}",htmlStr);
byte[] pdfBytes = new byte[0];
try {
pdfBytes = PDFUtil.pdfgenerate(htmlStr, ttcurl);
log.info("pdfBytes {}",pdfBytes);
} catch (Exception e) {
e.printStackTrace();
}
return pdfBytes;
}
PDFUtil
package com.qunji.sale.trade.pdf;
import cn.hutool.core.io.resource.ResourceUtil;
import com.itextpdf.text.FontProvider;
import com.itextpdf.text.io.StreamUtil;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.qunji.sale.common.utils.Environment;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.Map;
@Slf4j
public class PDFUtil {
private PDFUtil(){}
private volatile static Configuration configuration;
static {
if (configuration == null) {
synchronized (PDFUtil.class) {
if (configuration == null) {
configuration = new Configuration(Configuration.VERSION_2_3_28);
}
}
}
}
public static String freemarkerRender(Map dataMap, String ftlFilePath,String PROFILES_ACTIVE) {
Writer out = new StringWriter();
configuration.setDefaultEncoding("UTF-8");
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
try {
ClassPathResource res = new ClassPathResource(ftlFilePath);
InputStream in = res.getInputStream();
String folder = "D:/trade";
if(!PROFILES_ACTIVE.equals(Environment.DEV)){
folder = "/usr/local/static/tarde";
}
File file = new File(folder + File.separator + "file");
file.createNewFile();
FileUtils.copyInputStreamToFile(in,file);
configuration.setDirectoryForTemplateLoading(new File(file.getParent()));
configuration.setLogTemplateExceptions(false);
configuration.setWrapUncheckedExceptions(true);
Template template = configuration.getTemplate(file.getName(), "utf-8");
template.setEncoding("UTF-8");
template.process(dataMap, out);
out.flush();
return out.toString();
} catch (Exception e) {
log.error("error {}",e);
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static byte[] pdfgenerate(String htmlContent, String fontFile)throws Exception{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(htmlContent.getBytes("UTF-8")));
ITextRenderer iTextRenderer = new ITextRenderer();
// classpath 路径
//添加字体,以支持中文
ClassPathResource resource = new ClassPathResource(fontFile);
iTextRenderer.getFontResolver().addFont(resource.getURL().toString(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
ByteArrayOutputStream out = new ByteArrayOutputStream();
iTextRenderer.setDocument(doc, null);
iTextRenderer.layout();
iTextRenderer.createPDF(out);
byte[] bytes = out.toByteArray();
out.close();
return bytes;
}
}
注意 这里要把 Windows和linux的文件夹提前创建好 这里需要根据系统 来定义临时存放文件的文件夹路径
String folder = "D:/trade";
if(!PROFILES_ACTIVE.equals(Environment.DEV)){
folder = "/usr/local/static/tarde";
}
ftl
Title
| 姓名 | 交易编号 |
|---|---|
| ${userName!''} | ${orderCode!''} |
字体文件包下载地址
simsun.ttc字体文件 :链接:百度网盘 请输入提取码 密码:yhdo
如果是发送邮件附件则需要以下代码
bytefile则是转为pdf返回的byte数组
public EmailResult sendEmail(String to, String subject, String content,byte[] bytefile,String pdftitle){
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(alias+'<'+username+'>');
mimeMessageHelper.setTo(to);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(content);
final InputStreamSource attachmentSource = new ByteArrayResource(bytefile);
//DataSource dataSource = new ByteArrayDataSource(bytefile, "application/pdf");
mimeMessageHelper.addAttachment(pdftitle+".pdf", attachmentSource);
// mimeMessageHelper.addAttachment("询价单.pdf", inputStreamSource);
javaMailSender.send(mimeMessage);
return new EmailResult(true, "发送成功!");
}catch (Exception e) {
log.error("sendEmail方法发送邮件错误:" + e.getMessage());
return new EmailResult(false, "发送失败!");
}
}
参考文章
springboot html 动态数据转pdf_hlvy的博客-CSDN博客



