Skip to content

Instantly share code, notes, and snippets.

@WenderGalan
Last active March 12, 2020 21:10
Show Gist options
  • Save WenderGalan/5203285c701975322a5d6fa37572ae69 to your computer and use it in GitHub Desktop.
Save WenderGalan/5203285c701975322a5d6fa37572ae69 to your computer and use it in GitHub Desktop.
Generates a PDF based on an HTML page.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/canvas2image.min.js"></script>
</head>
<script language="javascript">
(function($){
$.fn.createPdf = function(parametros) {
var config = {
'fileName':'html-to-pdf'
};
if (parametros){
$.extend(config, parametros);
}
debugger
var quotes = document.getElementById($(this).attr('id'));
html2canvas(quotes, {
onrendered: function(canvas) {
var pdf = new jsPDF('p', 'pt', 'letter');
for (var i = 0; i <= quotes.clientHeight/980; i++) {
var srcImg = canvas;
var sX = 0;
var sY = 980*i;
var sWidth = 900;
var sHeight = 980;
var dX = 0;
var dY = 0;
var dWidth = 900;
var dHeight = 980;
window.onePageCanvas = document.createElement("canvas");
onePageCanvas.setAttribute('width', 900);
onePageCanvas.setAttribute('height', 980);
var ctx = onePageCanvas.getContext('2d');
ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);
var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);
var width = onePageCanvas.width;
var height = onePageCanvas.clientHeight;
if (i > 0) {
pdf.addPage(612, 791);
}
pdf.setPage(i+1);
pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));
}
pdf.save(config.fileName);
}
});
};
})(jQuery);
function createPDF() {
let site = document.getElementById("input").value
document.getElementById("content").src = site
window.setTimeout(() => {
debugger
$('#content').createPdf({
'fileName' : 'div_baixada'
});
}, 5000)
}
</script>
<body>
<input id="input" type="text"/>
<button type="button" class="btn btn-success" onclick="createPDF();">GERAR PDF</button>
<iframe id="content" style="width: 500px; height: 500px"/>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment