jsPDF

repository·master·Indexed 12 days ago

https://github.com/parallax/jspdf

A JavaScript library for generating PDF documents in both browser and Node.js environments. Version 4.2.1 supports various module formats (ES, UMD, Node), custom Unicode/UTF-8 fonts, and advanced PDF features like transformation matrices and patterns. It includes capabilities for adding images, rendering HTML to PDF, and configuring document properties such as orientation, units, and page formats.

Tokens
5K
Snippets
24
Records
31
Agent score
99%

What's inside jsPDF

  1. Understand jsPDF module formats

    master

    The dist folder contains different builds depending on your environment:

    • jspdf.es.*.js: Modern ES2015 module format.
    • jspdf.node.*.js: For Node.js environments. Uses file operations for loading/saving instead of browser APIs.
    • jspdf.umd.*.js: UMD module format, suitable for AMD or <script> tag loading.
    • polyfills*.js: Required for older browsers like Internet Explorer.

    In most build tools and Node.js, you can simply import jspdf and the environment will resolve the correct file automatically.

  2. Switch between Compat and Advanced API modes

    master

    jsPDF supports two API modes to balance legacy compatibility with new features:

    1. Compat mode (Default): Maintains the original MrRio API. This ensures compatibility with older plugins, but advanced features like transformation matrices and patterns are unavailable.
    2. Advanced mode: Provides the full API from the yWorks fork, enabling advanced features like patterns, FormObjects, and transformation matrices.

    You can switch modes temporarily using a callback pattern. jsPDF automatically reverts to the original mode after the callback executes.

    doc.advancedAPI(doc => {
      // Your code using advanced features like patterns or matrices
    });
    
    // or
    
    doc.compatAPI(doc => {
      // Your code using the legacy API
    });
  3. Configure file system permissions in Node.js

    master

    By default, jsPDF restricts reading files from the local file system in Node.js for security.

    Recommended approach: Use Node's native permission flags to enforce access at the runtime level:

    node --permission --allow-fs-read=... ./scripts/generate.js

    Note: You must include all imported JS files and dependencies in the --allow-fs-read flag.

    Fallback approach (not recommended): Manually set jsPDF.allowFsRead in your script:

    import { jsPDF } from "jspdf";
    
    const doc = new jsPDF();
    doc.allowFsRead = ["./fonts/*", "./images/logo.png"];
  4. How to enable hotfixes in jsPDF

    master

    jsPDF allows you to enable specific hotfixes (pre-baked solutions for specific use cases) by passing a hotfixes array to the jsPDF constructor options. Hotfixes are used to address specific issues without changing the core library behavior permanently until they are marked as accepted and made default.

    new jsPDF({
      hotfixes: ["px_scaling"]
    });
  5. Add custom Unicode/UTF-8 fonts

    master

    Standard PDF fonts only support the ASCII codepage. To use UTF-8 (e.g., for Chinese characters), you must integrate a custom .ttf font.

    Option 1: Using the Font Converter

    Use the fontconverter to convert a .ttf file into a JavaScript file containing a base64 encoded string. Add this generated file to your project and use setFont().

    Option 2: Loading .ttf via Fetch

    You can load a .ttf file as a binary string and add it directly to the Virtual File System (VFS):

    const doc = new jsPDF();
    
    // myFont should be the *.ttf font file loaded as a binary string
    const myFont = ... 
    
    // add font to jsPDF
    doc.addFileToVFS("MyFont.ttf", myFont);
    doc.addFont("MyFont.ttf", "MyFont", "normal");
    doc.setFont("MyFont");
  6. Install jsPDF via npm or unpkg

    master

    You can install jsPDF using npm or yarn for most modern development workflows. Alternatively, you can load it directly in a browser using the unpkg CDN.

    npm/yarn

    npm install jspdf --save
    # or
    yarn add jspdf

    unpkg (CDN)

    <script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>
    npm install jspdf --save
  7. Run jsPDF in Node.js

    master

    When using Node.js, use require to load the Node-specific version automatically. The save() method will write the file to the current working directory.

    const { jsPDF } = require("jspdf");
    
    const doc = new jsPDF();
    doc.text("Hello world!", 10, 10);
    doc.save("a4.pdf");
  8. Run the jsPDF + Vite project in development mode

    master

    To start the development server, run the dev script. Once running, open http://localhost:5173 in your browser and click the "Generate PDF" button to verify that PDF generation and downloads are working correctly in a Vite environment.

    npm run dev
  9. Build and preview the jsPDF + Vite production bundle

    master

    To test the production build of the project, run the build command followed by the preview command. After building, open http://localhost:4173 to verify the production assets work as expected.

    npm run build
    npm run preview
  10. Manage optional dependencies in Webpack

    master

    Certain features like the html method require optional dependencies (html2canvas, dompurify, canvg). jsPDF loads these dynamically. To prevent Webpack from automatically generating separate chunks for these if you don't intend to use them, define them as externals in your webpack.config.js.

    // webpack.config.js
    module.exports = {
      // ...
      externals: {
        // Only define the dependencies you are NOT using as externals!
        canvg: "canvg",
        html2canvas: "html2canvas",
        dompurify: "dompurify"
      }
    };
  11. Configure pattern transformations with GState and Matrix

    master
    Both ShadingPattern and TilingPattern accept optional gState (of type GState) and matrix (of type Matrix) parameters in their constructors. These allow you to control the graphics state and coordinate transformations applied to the pattern.