Last active
July 11, 2017 05:39
-
-
Save dev-jonghoonpark/8e1e13ede069b859a6c57b30b428d764 to your computer and use it in GitHub Desktop.
splited screen pdf using jsPDF and html2canvas without cutoff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- base source from "https://stackoverflow.com/a/34934497" --> | |
<script src="/resources/js/jspdf/html2canvas.js"></script> | |
<script src="/resources/js/jspdf/jspdf.js"></script> | |
<script src="/resources/js/jspdf/plugins/addimage.js"></script> | |
<script src="/resources/js/jspdf/FileSaver.js"></script> | |
<script> | |
const A4_WIDTH = 595; | |
const A4_HEIGHT = 842; | |
$(function () { | |
$('.total').click(function () { | |
var body = $("body")[0]; | |
var ratio = body.scrollWidth > A4_WIDTH ? body.scrollWidth / A4_WIDTH : 1; | |
html2canvas(body, { | |
onrendered: function (canvas) { | |
var pdf = new jsPDF('p', 'pt', 'a4'); | |
for (var i = 0; i <= body.scrollHeight / (A4_HEIGHT * ratio); i++) { | |
var srcImg = canvas; | |
var sX = 0; | |
var sY = A4_HEIGHT * ratio * i; | |
var sWidth = A4_WIDTH * ratio; | |
var sHeight = A4_HEIGHT * ratio; | |
var dX = 0; | |
var dY = 0; | |
var dWidth = A4_WIDTH * ratio; | |
var dHeight = A4_HEIGHT * ratio; | |
window.onePageCanvas = document.createElement("canvas"); | |
onePageCanvas.setAttribute('width', (A4_WIDTH * ratio).toString()); | |
onePageCanvas.setAttribute('height', (A4_HEIGHT * ratio).toString()); | |
var ctx = onePageCanvas.getContext('2d'); | |
ctx.clearRect(0, 0, onePageCanvas.width, onePageCanvas.height); | |
ctx.fillStyle = "#ffffff"; | |
ctx.fillRect(0, 0, onePageCanvas.width, onePageCanvas.height); | |
ctx.drawImage(srcImg, sX, sY, sWidth, sHeight, dX, dY, dWidth, dHeight); | |
var canvasDataURL = onePageCanvas.toDataURL("image/jpeg", 1.0); | |
if (i > 0) { | |
pdf.addPage(A4_WIDTH, A4_HEIGHT); | |
} | |
pdf.setPage(i + 1); | |
pdf.addImage(canvasDataURL, 'jpeg', 0, 0, A4_WIDTH, A4_HEIGHT); | |
} | |
pdf.save('example.pdf'); | |
} | |
}); | |
}) | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment