Skip to content

Commit 2c0b345

Browse files
committed
Create a separate canvas for page generation
1 parent 8bd5481 commit 2c0b345

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

src/html2pdf.js

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -162,30 +162,35 @@ var html2pdf = (function(html2canvas, jsPDF) {
162162
};
163163

164164
html2pdf.makePDF = function(canvas, pageSize, opt) {
165-
// return document.body.appendChild(canvas);
166-
167-
// Break the full canvas into pages, then reduce it to one page.
165+
// Calculate the number of pages and get the full canvas image.
168166
var ctx = canvas.getContext('2d');
169167
var pxFullHeight = canvas.height;
170168
var pxPageHeight = Math.floor(canvas.width * pageSize.inner.ratio);
171169
var nPages = Math.ceil(pxFullHeight / pxPageHeight);
172170
var imgFull = ctx.getImageData(0, 0, canvas.width, canvas.height);
173-
canvas.height = pxPageHeight;
171+
172+
// Create a one-page canvas to split up the full image.
173+
var pageCanvas = document.createElement('canvas');
174+
var pageCtx = pageCanvas.getContext('2d');
175+
pageCanvas.width = canvas.width;
176+
pageCanvas.height = pxPageHeight;
174177

175178
// Initialize the PDF.
176179
var pdf = new jsPDF(opt.jsPDF);
177180

178181
for (var page=0; page<nPages; page++) {
182+
// Trim the final page to reduce file size.
183+
if (page === nPages-1) pageCanvas.height = pxFullHeight % pxPageHeight;
184+
179185
// Display the page (fill with white a bit past the render edge just in case).
180-
ctx.fillStyle = '#FFFFFF';
181-
ctx.fillRect(-10, -10, canvas.width+20, canvas.height+20);
182-
ctx.putImageData(imgFull, 0, -page*pxPageHeight);
186+
pageCtx.fillStyle = '#FFFFFF';
187+
pageCtx.fillRect(-10, -10, pageCanvas.width+20, pageCanvas.height+20);
188+
pageCtx.putImageData(imgFull, 0, -page*pxPageHeight);
183189

184190
// Add the page to the PDF.
185191
if (page) pdf.addPage();
186-
var imgData = canvas.toDataURL('image/' + opt.image.type, opt.image.quality);
187-
pdf.addImage(imgData, opt.image.type, opt.margin[1], opt.margin[0],
188-
pageSize.inner.width, pageSize.inner.height);
192+
var imgData = pageCanvas.toDataURL('image/' + opt.image.type, opt.image.quality);
193+
pdf.addImage(imgData, opt.image.type, opt.margin[1], opt.margin[0]);
189194

190195
// Add hyperlinks.
191196
if (opt.enableLinks) {

0 commit comments

Comments
 (0)