Exporting Pages to PDF in a Vue.js 3 Project

Sometime we need to export frontend pages, such as report pages, to PDF. For this purpose, we’ll use html2Canvas and jsPDF in a Vue.js 3 project.
Prerequisites
Firstly, let’s install the required dependencies:
npm install html2canvas npm install jspdf
Visit the jsPDF GitHub and jsPDF Documentation for more details about jsPDF.
Implementation Steps
Import Dependencies:
Import the necessary dependencies into your project:
// utils/html2pdf.ts
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';Create htmlToPDF Function:
Create a function that takes the HTML element’s ID, title, and background color as parameters. This function will convert the HTML content to a canvas and then generate a PDF.
// utils/html2pdf.ts
export const htmlToPDF = async (
htmlId: string,
title: string = "Report",
bgColor = "#fff"
) => {
// ... function implementation
}Implement the PDF Generation:
Inside the htmlToPDF function, use html2Canvas to capture the HTML content, calculate the required dimensions, and generate the PDF using jsPDF.
// utils/html2pdf.ts
export const htmlToPDF = async (
htmlId: string,
title: string = "Report",
bgColor = "#fff"
) => {
// ... function implementation
// Use html2Canvas to capture the HTML content
let canvas = await html2canvas(pdfDom, {
scale: 2,
useCORS: true,
backgroundColor: bgColor,
});
// Calculate dimensions and generate PDF using jsPDF
let pageHeight = (canvas.width / A4Width) * A4Height;
// ... remaining code
}Include Watermark (Optional):
If you want to add a watermark to the PDF, you can include the following code:
// utils/html2pdf.ts
// ... within the function
const ctx: any = canvas.getContext('2d');
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.rotate((20 * Math.PI) / 180);
ctx.font = '20px ComicSansMS';
ctx.fillStyle = 'rgba(184, 184, 184, 0.8)';
for (let i = canvas.width * -1; i < canvas.width; i += 240) {
for (let j = canvas.height * -1; j < canvas.height; j += 200) {
ctx.fillText('Watermark', i, j);
}
}Integrate with Vue Component:
Finally, in the Vue component where you want to enable PDF export, include the htmlToPDF function.
<!-- YourComponent.vue -->
<template>
<div id="report-id" style="padding: 20px 0;">
<!-- Your HTML content -->
</div>
<button @click="exportToPDF">Export to PDF</button>
</template>
<script>
import { htmlToPDF } from '@/utils/html2pdf';
export default {
methods: {
exportToPDF() {
htmlToPDF('report-id', 'report');
},
},
};
</script>And that’s it! You should now be able to export your Vue.js 3 project pages to a PDF by clicking the specified button. Feel free to customize the function and styles according to your project’s requirements.





