Jspdf: How to set bottom and top margin for addImage

Created on 26 Nov 2015  路  2Comments  路  Source: MrRio/jsPDF

I am using the below code to to generate pdf. I can set top margin in first page but I could not found a way to set bottom margin in first page. In second page I could not set the both top and bottom margin. please suggest a way.
function generatePdf(divId)
{
var doc = new jsPDF('p', 'mm');
var elemen = document.getElementById(divId);
html2canvas((elemen), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var d = new Date();
var n = d.toLocaleDateString();
doc.page=1; // use this as a counter.
function footer(){
doc.setFontSize(8);
doc.text(185,295, n); //print number bottom right
doc.page ++;
};
var imgWidth = 160;
var pageHeight = 297;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var position = 0;
doc.addImage(imgData, 'PNG',25, 10, imgWidth, imgHeight);
footer();
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(imgData, 'PNG', 25, position, imgWidth, imgHeight);
footer();
heightLeft -= pageHeight;
}
doc.save('sample-file.pdf');
}
});
}

Most helpful comment

@bjraj @arasabbasi Have you got any solution to add Margin from second page onwards

All 2 comments

@bjraj @arasabbasi Have you got any solution to add Margin from second page onwards

You can do the paging based on the canvas. That means use "getImageData" from the canvas and create a new one for the content to the page.

    var getPageCanvas = function(canvas, pageWidth, pageHeight, pageNo){
        var pageImageWidth = canvas.width;
        var pageImageHeight = pageHeight * pageImageWidth/pageWidth;

        var ctx = canvas.getContext('2d');
        var buffer = ctx.getImageData(0, pageNo * pageImageHeight, pageImageWidth, pageImageHeight);
        var pageCanvas = document.createElement('canvas');
        pageCanvas.width = pageImageWidth;
        pageCanvas.height = pageImageHeight;
        var pageCanvasCtx = pageCanvas.getContext('2d');
        pageCanvasCtx.putImageData(buffer, 0, 0);

        return pageCanvas;
    };

And repeatedly add the new canvas to the document.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

NoFootDancer picture NoFootDancer  路  3Comments

centurianii picture centurianii  路  4Comments

glaier picture glaier  路  3Comments

andmaltes picture andmaltes  路  4Comments

yankeeBrit picture yankeeBrit  路  3Comments