Convert Excel file to PDF (NODEJS)
I have been searching about conversion of excel files into PDFs by using NodeJS. After spending a day on it I finally found out the actual procedure and I thought I should share it with everyone, people who read it would take few hours to get it on track. Just follow the steps.
- Install NPM Packages
We would need to play with xlsx to read an excel file and create JSON from it and we would need pdfmake package to create your PDF File. We would also need fileSystem(fs) to create writeStreams for us and that would help us to write PDF file in the end.
npm i pdfmake xlsx
2. Create a main file and import packages.
3. Import fonts
This step is the most important step because pdfmake package needs fonts to create the PDF File. So install Roboto font from google fonts from the below link and create a directory in the root so that we can use those fonts.
3. Import Excel file data and convert it into JSON Object
4. Create a Header for PDF
We always have a header in an excel file so we need to create a header in PDF also. We would need to define font-size(optional) and bold property too(optional).
5. Create an Array of Objects for PDF from JSON of excel file
6. Define PDF Object
This PDF Contains the PDF content, PDF Layout, Table properties to read about the Table in detail, please follow the link of documentation.
https://pdfmake.github.io/docs/0.1/document-definition-object/tables/
7. Save PDF File
FileSystem Streams can help us to identify the completion of process. So if we want to do something after completion of file saving then we can do that in
writeStream.on(“finish”,()=>{
//do wharever you want
});