1

I have been using JSPDF to generate pdf document based on some html. Earlier using jspdf fromHTML Api, we could give margins like this

 var margins2 = { top: 415, bottom: 10, left: 55, width: 300 }; doc.fromHTML(reactListContent, margins2.left, margins2.top, { 'width': margins2.width, 'elementHandlers': specialElementHandlers }, margins2); 

But, in the new .html API , how can i provide margins, width and height. The new API is like

var pdf = new jsPDF('p', 'pt', 'letter'); pdf.html(document.getElementById('html'), { callback: function (pdf) { console.log("how to get margins"); } }); 

2 Answers 2

1

If you look at the source code of jspdf.debug.js, html.js has the options for x and y offsets.

opt: { filename: 'file.pdf', margin: [0, 0, 0, 0], enableLinks: true, x: 0, y: 0, html2canvas: {}, jsPDF: {} } 

So you can set the x and y coordinates like this:

pdf.html(document.getElementById('html'), { x: 36, y: 36, callback: function () { // pdf.save('test.pdf'); window.open(pdf.output('bloburl')); // to debug } }); 

Unfortunately, I can't do the same by modifying the margin: [0, 0, 0, 0]. Looks like they are still working on this issue. So the short answer is NOT YET.

A work-around is to calculate the scale of html2canvas by margin:

let pdf = new jsPDF('p', 'pt', 'a4'); let margin = 36; // narrow margin - 12.7 mm let srcwidth = document.getElementById('html').scrollWidth; let scale = (595.28 - margin * 2) / srcwidth; // a4 pageSize 595.28 pdf.html(document.getElementById('html'), { backgroundColor: 'lightyellow', html2canvas: { scale: scale // default is window.devicePixelRatio, }, x: margin, y: margin, callback: function () { window.open(pdf.output('bloburl')); } }); 
Sign up to request clarification or add additional context in comments.

Comments

0

Using jsPDF to generate a PDF matching HTML page dimensions (not accounting for multi-pages), including rendered images. Script depends on jsPDF v2.5.1 and html2canvas 1.4.1 (for rendering canvases, ie. for images etc): // Create unconfigured PDF. var pdf = new jsPDF();

// Generate PDF content from HTML body. pdf.html (document.querySelector("body"), { // Config PDF page to match HTML page dimensions. margin: [0, 0, 0, 0], // PDF margins x: 0, y: 0, // PDF content origin offset from PDF page origin width: pdf.internal.pageSize.getWidth(), // Generated PDF document's width in jsPDF units windowWidth: window.innerWidth // Page width in its browser window in CSS pixels } ); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.