jsPDF can't get any styling to work

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

I'm new to using jsPDF but and for the life of me I can't get any css to apply to this thing! I've tried inline, internal, and external all to no avail! I read in another SO post that since it's technically printing stuff to a file I need a print style sheet, and that didn't work either.

I have a very basic page that I'm just trying to get any CSS to work with: JS:

HTML:

     
Download Maybe?

We support special element handlers. Register them with jQuery-style

And finally the stylesheet that is external:

h1{     color: red; } div{     color: red; }

I'm sure all is getting included correctly, and that there are no errors, already checked all of that. Is there like some extra function I need to call to get the css to work as well? Let me know please! Thanks alot! Any other tips you may have are also appreciated!

EDIT: This is the exact webpage:

              
Download Maybe?

We support special element handlers. Register them with jQuery-style

回答1:

I think the problem is that you use media="print" instead of media="screen". Try making two seperate files, one for print and one for the screen:

The screen one will contain the styling for the page as seen in a browser. The print one will contain the styling for when you print your page, or in this case saving it as a PDF.

EDIT

I checked the jsPDF website but I think they don't support CSS. You could do something like this to create a document with different text colors though:

doc.setFontSize(22); doc.setTextColor(255, 0, 0); doc.text(20, 20, 'This is a title');  doc.setFontSize(16); doc.setTextColor(0, 255, 0); doc.text(20, 30, 'This is some normal sized text underneath.');

Put this code right under var doc = new jsPDF('landscape'); in your script.



回答2:

You can capture a screenshot with jsPDF, but you'll need html2canvas as well. Use html2canvas to convert the html to canvas and grab the image content. Create an empty pdf with jsPDF and add the html image content into the pdf and save:

html2canvas(*html*, {   onrendered: function(canvas) {     const contentDataURL = canvas.toDataURL('image/png')     let pdf = new jsPDF()     pdf.addImage(contentDataURL, 'JPEG', 20, 20)     pdf.save('form.pdf')   } })

This will retain all CSS but the quality will suffer a little (blurry).



回答3:

you can try this option, that uses jsPDF, html2canvas and html2pdf libraries

from its README:

include this files:

and then you can generate your pdf by running:

html2pdf($('body').get(0), {    margin:       1,    filename:     'myfile.pdf',    image:        { type: 'jpeg', quality: 0.98 },    html2canvas:  { dpi: 192, letterRendering: true },    jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' } });


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!