HTML到PDF与CSS包括

HTML to PDF with CSS included

本文关键字:CSS 包括 PDF HTML      更新时间:2023-09-26

我正在寻找一种使用jsPDF将我的页面转换为PDF文档的方法,但是现在我无法转换任何CSS样式。只有文字,没有图片。

这是我现在使用的代码

    var specialElementHandlers = {
        '#ignorePDF': function (element,renderer) {
            return true;
        }
    };
    var doc = new jsPDF();
    doc.fromHTML($('#page-with-images').get(0), 20, 20, {'width': 500, 'elementHandlers': specialElementHandlers,});
    doc.save("Test.pdf");

但是结果不是我想要的,因为没有包含样式。如何解决这个问题?

试试这个

var pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML($("#content"), function() {
  var output = pdf.output("datauristring");
  alert(output);
  //pdf.output("datauri"); //This will output the PDF in a new window
});
div {
  width: 100%;
  background-color: lightblue;
  padding: 15px;
  border: 2px solid black;
}
p {
  background-color: limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
<body>
  <div id="content">
    <div>
      <div>
        <div>
          <div>
            <p id="to-pdf">HTML content...</p>  
          </div>
        </div>
      </div>
    </div>
  </div>
</body>