javascript - JS中的HTML到PDF使用变量
问题描述
这是我的第一篇文章,因为我被卡住了,我在这里或网络上都没有找到解决方案。
我想使用 JS 将 HTML 转换为 PDF。我正在搜索,最好的选择似乎是 HTML2canvas 和 JSpdf。但我的想法是我的 HTML 存储在一个变量中:
var test = '<html><head><script type="text/javscript">var number = 123;</script></head><body>
<h1>"the value for number is: " + number</h1></body></html>'
我的变量要复杂得多,它包含 CSS 和样式,但这只是为了理解。然后,当我尝试将其转换为画布时,它不会转换。
const filename = 'ThisIsYourPDFFilename.pdf';
html2canvas(test).then(canvas => {
let pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
pdf.save(filename);
});
有谁知道为什么会这样?也许这是一个非常愚蠢的问题,但我不知道如何避免错误。
先感谢您。
解决方案
您使用字符串作为 html2canvas 的参数,但它需要 HTML 元素:
html2canvas(document.body).then(function(canvas) {
document.body.appendChild(canvas);
});
我修改了你的代码:
const html2canvas = require("html2canvas");
const jsPDF = require("jspdf");
html2canvas(document.getElementById("screenshot"), { scale: 1 }).then(
(canvas) => {
document.body.appendChild(canvas);
const filename = "ThisIsYourPDFFilename.pdf";
let pdf = new jsPDF("p", "mm", "a4");
pdf.addImage(canvas.toDataURL("image/png"), "PNG", 0, 0);
pdf.save(filename);
document.body.removeChild(canvas);
}
);
正文应包含带有 id 屏幕截图的元素:
<div id="screenshot">
Content
</div>
更新:
根据这个资源jsPDF 有方法fromHTML
,所以你可能不需要 html2canvas
var doc = new jsPDF();
var elementHTML = $('#contnet').html();
var specialElementHandlers = {
'#elementH': function (element, renderer) {
return true;
}
};
// note here that it uses html
doc.fromHTML(elementHTML, 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
// Save the PDF
doc.save('sample-document.pdf');
推荐阅读
- apache-spark - Spark Cassandra 优化连接
- sql - 如何检查行的连续性?
- reactjs - ReactDOMServer.renderToStaticMarkup() 与 ReactDOM.render()
- amazon-web-services - Elastic Beanstalk 部署挂钩:获取用户的用户名
- authentication - AddAuthentication 和 AddAuthenticationCore 有什么区别?
- c++ - 如何运行多行cin?
- javascript - 在 NodeJS 中将多个数据库查询优化为一个
- git - 使用 GIT 通过拖放方法替换连接到 Azure Devops (web) 的源/repo 文件夹(本地)中的文件
- java - 我有一个涉及 Android 中的 Handle.postDelay 函数的问题
- c - (int*) malloc(n*sizeof(int)) 和 int *array = malloc(sizeof(int)*n) 的区别