首页 > 解决方案 > 使用 React 和 .Net Core Web Api 作为附件发送 PDF

问题描述

我在网上发现了很多过时的选项,所以只是徘徊什么应该是转换 DOM 的最佳方法,作为 PDF 附件,然后通过电子邮件发送。我使用 React 作为前端,使用 .Net Core Web Api 作为后端。

提前致谢 :)

标签: reactjsasp.net-coreasp.net-core-webapiemail

解决方案


从Github下载 jsPDF包括以下脚本:

jspdf.js
jspdf.plugin.from_html.js
jspdf.plugin.split_text_to_size.js
jspdf.plugin.standard_fonts_metrics.js

如果你想忽略某些元素,你必须用一个 ID 标记它们,然后你可以在 jsPDF 的特殊元素处理程序中忽略它。因此,您的 HTML 应如下所示:

<!DOCTYPE html>
<html>
  <body>
    <p id="ignorePDF">don't print this to pdf</p>
    <div>
      <p><font size="3" color="red">print this to pdf</font></p>
    </div>
  </body>
</html>

然后使用以下 JavaScript 代码在弹出窗口中打开创建的 PDF:

var doc = new jsPDF();          
var elementHandler = {
  '#ignorePDF': function (element, renderer) {
    return true;
  }
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
    source,
    15,
    15,
    {
      'width': 180,'elementHandlers': elementHandler
    });

doc.output("dataurlnewwindow");

要添加的一件非常重要的事情是您丢失了所有样式信息 (CSS)。幸运的是,jsPDF 能够很好地格式化 h1、h2、h3 等,这对我的目的来说已经足够了。此外,它只会打印文本节点内的文本,这意味着它不会打印 textareas 等的值。例子:

<body>
  <ul>
    <!-- This is printed as the element contains a textnode -->        
    <li>Print me!</li>
  </ul>
  <div>
    <!-- This is not printed because jsPDF doesn't deal with the value attribute -->
    <input type="textarea" value="Please print me, too!">
  </div>
</body>

在此链接的帮助下附加 pdf 并发送电子邮件


推荐阅读