SoFunction
Updated on 2025-04-14

Vue uses html2canvas and jspdf to implement PDF file export

Implement the functions of exporting PDF files, resizing file page size and page orientation in Vue projects. Use html2canvas to convert HTML content into pictures, and then use jspdf to add pictures to PDF files. The following are detailed implementation steps and code examples:

Step 1: Install dependencies

First, install html2canvas and jspdf in the project:

npm install html2canvas jspdf

Step 2: Create Vue Components

Here is a complete Vue component example that includes the functions of exporting PDFs, resizing pages, and orientation:

<template>
  <div>
    <!-- Select the page size drop-down box -->
    <select v-model="selectedPageSize">
      <option value="a4">A4</option>
      <option value="a3">A3</option>
      <option value="letter">Letter</option>
    </select>
    <!-- Select the drop-down box for page orientation -->
    <select v-model="selectedPageOrientation">
      <option value="portrait">Vertical</option>
      <option value="landscape">Horizontal</option>
    </select>
    <!-- Export PDF Buttons -->
    <button @click="exportToPDF">Export为 PDF</button>
    <!-- 需要Export为 PDF Content area -->
    <div >
      <h1>这是要Export为 PDF Contents</h1>
      <p>More text can be added here、picture、Tables and other elements。</p>
    </div>
  </div>
</template>

<script>
// Introduce html2canvas to convert HTML elements into canvas imagesimport html2canvas from 'html2canvas';
// Introduce jsPDF to create and save PDF filesimport jsPDF from 'jspdf';

export default {
  data() {
    return {
      //Storing the page size selected by the user, default to A4      selectedPageSize: 'a4',
      //Storing the page direction selected by the user, default to portrait      selectedPageOrientation: 'portrait'
    };
  },
  methods: {
    async exportToPDF() {
      // Get HTML elements that need to be exported as PDF      const element = ('contentToExport');
      try {
        // Use html2canvas to convert HTML elements to canvas images        const canvas = await html2canvas(element);
        // Convert canvas images to base64 encoded PNG image data        const imgData = ('image/png');

        // Create a jsPDF instance based on the page size and direction selected by the user        const pdf = new jsPDF({
          orientation: , // Page direction          unit: 'mm', // Unit in millimeters          format:  // Page size        });

        // Get the width and height of the PDF page        const pdfWidth = ();
        const pdfHeight = ();

        // Calculate the width and height of the image to fit the image to the page in proportion        const imgWidth = pdfWidth;
        const imgHeight = ( * imgWidth) / ;

        let heightLeft = imgHeight;
        let position = 0;

        // Add image to the first page PDF        (imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pdfHeight;

        // If the image height exceeds one page, pagination processing is performed        while (heightLeft >= 0) {
          position = heightLeft - imgHeight;
          ();
          (imgData, 'PNG', 0, position, imgWidth, imgHeight);
          heightLeft -= pdfHeight;
        }

        // Save the PDF file with the file name        ('');
      } catch (error) {
        //Catch and print possible errors during export        ('An error occurred while exporting PDF:', error);
      }
    }
  }
};
</script>

<style scoped>
/* Add style to content areas that need to be exported */
#contentToExport {
  padding: 20px;
  border: 1px solid #ccc;
  margin-top: 20px;
}
</style>

Code explanation

Template part (<template>):

The two select elements are used to select page size and page orientation, respectively, and bind to the component's data selectedPageSize and selectedPageOrientation through the v-model directive.

A button that triggers the exportToPDF method when clicked to perform PDF export operation.

A div element whose id is contentToExport, and the content inside this element will be exported as PDF.

Script part (<script>):

The data function returns two data items, respectively storing the page size and page direction selected by the user.

The exportToPDF method is the core logic:

Use Get the HTML element to export.

Call html2canvas to convert HTML elements into canvas images and convert them into base64-encoded PNG image data.

Create a jsPDF instance based on the page size and orientation selected by the user.

Calculate the width and height of the image so that it fits proportionally to the page.

Add an image to the PDF and perform pagination if the image height exceeds one page.

Finally, use the method to save the PDF file.

Style part (<style>):

Added some styles to the #contentToExport element so that it has borders and inner margins on the page.

How to use

Save the above code as a Vue component (for example), then introduce it in other components and use:

<template>
  <div>
    <ExportPDF />
  </div>
</template>

<script>
import ExportPDF from './';

export default {
  components: {
    ExportPDF
  }
};
</script>

This is the article about Vue using html2canvas and jspdf to implement PDF file export. For more related Vue PDF export content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!