本人菜鸡程序员一枚,记录工作中遇到的一些问题大家一起参考,望指正。
公司要求生成手机pdf发送给用户,开始使用使用html2canvas和jspdf插件实现但这货有很多的局限性,比如:容易出现截断问题,手机自动适应a4
考虑了很久还是通过前端传入html后端生成pdf,可以完美解决问题
前端
// 获取到要生成pdf的节点
let aaa = this.$refs['pdfDom'].innerHTML
//拼接html ...为页面的css
var htmlStr = "<!DOCTYPE html>\n"
+ "<html lang=\"en\">\n"
+ "<head>\n"
+ " <title>Title</title>\n "
+ "<style type=\"text/css\">\n"
+ " body {font-family: SimSun;}\n"
+ " @page{size:a4}\n"
....
+ aaa + "</body>\n" + "</html>";
//然后发送请求
。。。
后端
<!--邮件发送-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
spring:
mail:
# 此处填写SMTP服务器
host: smtp.qq.com
# 编码
default-encoding: UTF-8
# 此处填写,写信人的账号
username: ***@qq.com
# 此处填写16位STMP口令
password: ***
# 发件人
fromaddress: ***@qq.com
smtp:
auth: true
starttls:
enable: true
required: true
@Resource
IMessageTemplateService messageTemplateService;
@ApiOperation("发送带附件的邮件")
@PostMapping("/sendAttachmentsMail")
public Result sendAttachmentsMail(@RequestBody MailReq mailReq) {
if (mailReq.getAttachments() == null) {
return ResultGenerator.genFailRes("页面数据错误");
}
String s = MyUtil.generateToken();
String filePath="D:\\pdf\\"+s+".pdf";
// 生成pdf
PDFUtil.htmlToPDF(new ByteArrayInputStream(mailReq.getAttachments().getBytes()), filePath);
// MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(mailReq.getAttachments());
messageTemplateService.sendAttachmentsMail(mailReq.getToUser(),"尊敬的用户你好","感谢您光临本院,你的报告请在附件中查看",filePath);
//删除发送完了的pdf
File file = new File(filePath);
if (file.exists()) {//文件是否存在
file.delete();
}
return ResultGenerator.genSuccessRes();
}
/** * pdf工具类 */
public class PDFUtil {
public static void htmlToPDF(InputStream htmlFileStream, String pdfPath) {
try {
// InputStream htmlFileStream = new FileInputStream(htmlString);
// 创建一个document对象实例
Document document = new Document();
// 为该Document创建一个Writer实例
PdfWriter pdfwriter = PdfWriter.getInstance(document,
new FileOutputStream(pdfPath));
pdfwriter.setViewerPreferences(PdfWriter.HideToolbar);
// 打开当前的document
document.open();
InputStreamReader isr = new InputStreamReader(htmlFileStream, "UTF-8");
XMLWorkerHelper.getInstance().parseXHtml(pdfwriter, document,htmlFileStream,null,null,new MyFontsProvider());
//XMLWorkerHelper.getInstance().p
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// public static void main(String[] args) throws Exception {
// PDFUtil.htmlToPDF("D:\\pdf\\cc.html", "D:\\pdf\\a.pdf");
// }
}
/** * 处理中文不显示和乱码问题 */
class MyFontsProvider extends XMLWorkerFontProvider {
public MyFontsProvider(){
super(null, null);
}
@Override
public Font getFont(final String fontname, String encoding, float size, final int style) {
String fntname = fontname;
if (fntname == null) {
fntname = "宋体";//windows下
//fntname = "fontFile/simsun.ttf";//linux系统下
}
if (size == 0) {
size = 4;
}
return super.getFont(fntname, encoding, size, style);
}
}
/**
* 带附件的邮件
* @param to 收件人
* @param subject 主题
* @param content 内容
* @param filePath 附件
*/
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
// helper.addAttachment(filePath.getOriginalFilename(), filePath);
helper.addAttachment(fileName, file);
javaMailSender.send(message);
//日志信息
log.info("邮件已经发送。");
} catch (MessagingException e) {
log.error("发送邮件时发生异常!", e);
}
}