online pdf maker / generator.
It is hard to make clientside apps. It needs to get more libraries and stackoverflow (for me)🤓.
I was also trying to create clientside pdf generator and I found very use ful library.which is jsPDF.So,I taken it and started to make app.
Starting using jsPDF
It was also not simple to implement library.Mainly the photo is not being fit on the page of pdf file.
let me show you example .
In this screenshot you can see the photo is going out of the pdf page
I searched it on Google but no one written article on it and also jsPDF not given solution on this problem.
So, I started solving this problem.
Ratio
It's important to know the ratio
of image height as width so we can derive the small scale of the image which will fit on the page of pdf
here how to get ratio of image
Note : we have to get ratio of image exact after image upload so, we can be able to use it globally whenever we wanted..
Let's code it
<inputtype="file"onchange="getratio(this.files"/>
varimages_to_convert=[]vargetRatio=(files)=>{// Note files is json object not array objectfor(letfileofObject.values(files)){letreader=newFileReader();reader.onloadend=()=>{letimgsrc=reader.result;addImageToPdf(imgsrc);}reader.readAsDataUrl(file);}functionaddImageToPdf(src){// src is data url of imageletimg=newImage();img.onload=()=>{images_to_convert.push({src:img.src,height:img.height,width:img.width})// Now successfully ratio of height as width is noted}img.src=src;}
It was how I noted Ratio.
Making image fit on page
Image by icons8
Now we have ratio of image.only we need is page height and width size.
A4 page have width 210mm and height 300mm so the max is 300mm*210mm.
constmax={height:300,width:210}
We have know that the image height and width is in pixels but this doesn't Matter because it's in ratio.
Because , Height as well as width decrease or increase at same time so ratio will in same proportion.
Rendering
Now things we have are
Max height and width
Ratio of image height as width
If width of page is smaller than image width then image width will be page width similarly , if height of page is smaller than image height then image height is page hei axis.
Let me show in code
varrender=()=>{vardoc=newjsPDF("p","mm","a4");image_to_convert.forEach(img=>{// img is json that we stored previouslyletheight=img.height,width=img.width,src=img.src,ratio=img.height/img.width;if(height>max.height||width>max.width){if(height>width){height=max.height;width=height*(1/ratio);// Making reciprocal of ratio because ration of height as width is no valid here needs width as height}elseif(width>height){width=max.width;height=width*ratio;// Ratio is valid here }}doc.addImage(src,"png",0,0,width,height);doc.addPage("p","mm","a4");// Now successfully fitted image on page // I will prefer to use mm instead px});doc.save("download.pdf");}