Download a Vuejs view in PDF format

Wajiha Abid
2 min readJul 18, 2022

Nowadays frameworks are much powerful to held some computations and reduce server-side load. So now better requesting servers to download file, you can download directly. There are lot of times we have requirement to download invoices, receipts or anything in pdf format. So we can achieve this by simply converting the HTML to PDF.

This could be achieve simply in 3 steps.

Step 1:

Install the library named jsPdf , it gives several options of pdf generation. We will look into only html to pdf generator.

npm i jspdf

Step 2:

In the parent container add the ref property named anything as following:

ref is a special attribute, similar to the key attribute. It allows us to obtain a direct reference to a specific DOM element or child component instance after it's mounted. Through the ref attribute we will access the container in the jspdf library method which we will explore below.

STEP 3:

Now we will create a function named download which will be hit as we click the button. download function holds the following definition.

Other properties like width, x, y would set the content, if you want the content to be downloaded with css then convert html to canvas, you can explore the jsPdf option of html2canvas for better understanding.

Now at last connect the download function to the download button, and voila!🍻 Like this your html would be downloaded in pdf.

Conclusion:

This how you can download the html into pdf in 3 small steps. This is not just specific to vuejs, it could be used with any other framework just the accessing html method will change. There are lot more options in jsPDF like html2canvas, width, height etc, you can explore it in the doc.

You can find the code in this repo and feel free to add your opinions to it.

--

--