9

I am trying to use the JsPdf library to create a pdf based on html elements. I am wanting to know if it is possible to do with a div border or if i have to use the doc.line property and essentially draw each line around my div. I.E.

var doc = new jsPDF() doc.line(20, 20, 60, 20) 

I would much rather use <div style="border: solid; width: 300px ">

Has anyone had any luck with this?

Here is my Fiddle

1
  • My solution does what you asked, getting css into the pdf. Is there anything I can do to improve my answer? Commented Aug 31, 2017 at 16:40

4 Answers 4

3
+100

How about using jsPdf in conjunction with Html2Canvas? Render the html to canvas, then add the canvas to the pdf as an image like so:

var img = canvas.toDataURL("image/png"); doc.addImage(img, 'JPEG', 300, 200); doc.save('test.pdf'); 

See fiddle for full example: http://jsfiddle.net/nLLuvnwL/

Sign up to request clarification or add additional context in comments.

Comments

2

Instead of drawing each lines you can use doc.rect to draw the rectangle. You can also change the border width using doc.setLineWidth.

doc.setLineWidth(2); doc.rect(10, 20, 150, 75); doc.save('sample-file.pdf'); 

See example here http://jsfiddle.net/508p61r6/5/

1 Comment

If this isn't working for anybody, make sure the final argument isn't 'F' alone, or the stroke will be disregarded. You need to either remove that argument, or change it to 'FD'.
0
for (var i=1;i<pdf.internal.pages.length;i++){ pdf.internal.pages[i].push("0.00 595.28 841.89 -595.28 re"); pdf.internal.pages[i].push("S"); } 

1 Comment

Could you describe what this does? Otherwise, it will not be helpful to others.
0

Found out the solution to this,putting a rectangle as border for each pdf page and also starting the second page and other pages from a litte down by making difference in pageHeight,hope this will resolve for few...

html2canvas(myCanvas, { useCORS: false }, { allowTaint: true }).then(function (canvas) { var imgWidth = 210; var pageHeight = 290; var imgHeight = canvas.height * imgWidth / canvas.width; var heightLeft = imgHeight; var doc = new jsPDF('p', 'mm'); var position = 0; var pageData = canvas.toDataURL('image/jpeg', 1.0); var imgData = encodeURIComponent(pageData); doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight); doc.setLineWidth(5); doc.setDrawColor(255, 255, 255); doc.rect(0, 0, 210, 295); heightLeft -= pageHeight; while (heightLeft >= 0) { position = heightLeft - imgHeight; doc.addPage(); doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight); doc.setLineWidth(5); doc.setDrawColor(255, 255, 255); doc.rect(0, 0, 210, 295); heightLeft -= pageHeight; } doc.save('file.pdf'); });}; 

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.