jsPDF icon indicating copy to clipboard operation
jsPDF copied to clipboard

How to set bottom and top margin for addImage

Open bjraj opened this issue 11 years ago • 2 comments

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'); } }); }

bjraj avatar Nov 26 '15 07:11 bjraj

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

lahotiarpit avatar Mar 26 '18 09:03 lahotiarpit

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.

libofeng avatar Nov 07 '19 15:11 libofeng