我正在尝试使用jsPDF将div值下载到PDF中这里是我编写的代码:
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="jsPDF.js"></script>
<script>
$(function () {
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
});
</script>
</head>
<body>
<div id="content">
<h3>Hello, this is a H3 tag</h3>
<p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>
</body>
</html>
但是点击按钮时没有发生任何事情...我已经从this link下载了jsPDF。
我无能为力,请有人帮助我。
答案 0 :(得分:8)
从https://github.com/MrRio/jsPDF/tree/master/dist
中选择jspdf.min.js
然后这应该有效:
....
<script src="jspdf.min.js"></script>
<script>
$(function () {
$('#cmd').click(function () {
var doc = new jsPDF();
doc.addHTML($('#content')[0], 15, 15, {
'background': '#fff',
}, function() {
doc.save('sample-file.pdf');
});
});
});
</script>
....
答案 1 :(得分:1)
var http = require('http');
// var data = require('fs').readFileSync(__dirname + '/index.html', 'utf8');
http.createServer(function (req, res) {
if (req.url === '/') {
res.writeHead(200, {"content-type": "text/html"});
var html = require('fs').createReadStream(__dirname + '/index.html');
html.on('data', function (chunk) {
res.write(chunk);
})
}
else if (req.url === '/api') {
var obj = {
firstname: 'John',
lastname: 'Smith'
};
res.writeHead(200, {"content-type": "application/json"});
res.write(JSON.stringify(obj));
}
else {
res.writeHead(404, {"content-type": "text/plain"});
res.write("Error 404: Page not found.");
res.end();
}
}).listen(1337, "127.0.0.1");
console.log('Server listening on port 1337');
这是一个HTML工作我测试了很多次。并使用相同的代码。
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js"></script>
<script type="text/javascript" src="http://mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script>
<script type="text/javascript" src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$('#download').click(function() {
html2canvas($("#canvas"), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL('image/png');
$("#imgRes").attr("src", imgData);
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
}
});
});
});
});//]]>
</script>