简体   繁体   中英

Insert jpg image and create pdf using jsPDF

I want to insert jpg image on creation of pdf document, using jsPDF library. I tried to use this code:

var doc = new jsPDF();

var niceimage = new Image();

niceimage.src = '/resources/images/myimage.jpg';

doc.text(10, 10, 'Hello world!');

doc.addImage(niceimage, 'JPEG', 10, 10, 150, 76);

doc.save('a4.pdf');

I get message that it is not jpg image. Any thoughts?

Seems that file myimage.jpg cannot be used directly in jsPDF, according to my research. Image should be rather, converted to base64 file, and used that way in jsPDF. There is a great tool that I find for converting both jpg and png files here https://www.base64-image.de/ to base64.

Since those files are quite bulky, they will increase size of your javascript file. I find a solution for that, to put content (base64) of myimage.jpg file inside myimage.js:

var myImage = 'data:image/jpeg;base64,/9j/4QAYR..very..very....long...string...'

include that file inside your html file:

<script type="text/javascript" src="/js/myimage.js"></script>

Inside your main javascript file you can write:

var doc = new jsPDF();

doc.text(10, 10, 'Hello world!');

doc.addImage(myImage, 'JPEG', 10, 30, 150, 76);

doc.save('a4.pdf');

You will end-up with Hello world! and image underneath.

If you a new to jsPDF you can learn more at https://parall.ax/products/jspdf

Hope that helps a bit ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM