html-to-pdfmake

repository·master·Indexed 20 days ago

https://github.com/aymkdn/html-to-pdfmake

A utility library that converts HTML strings into PDFMake document definitions, allowing developers to generate PDFs using HTML/CSS structures instead of manually constructing complex JSON objects. Supports custom tag processing, default style overrides, automatic table sizing, and multi-column layouts via data-pdfmake attributes. Compatible with both web browsers and Node.js (requires jsdom).

Tokens
5K
Snippets
15
Records
22
Agent score
21%

What's inside html-to-pdfmake

  1. Create multi-column layouts using columns

    master

    To utilize PDFMake's columns feature, wrap your content in a div with the attribute data-pdfmake-type="columns". You can then use data-pdfmake on child divs to control their relative widths (e.g., using "*" for flexible width).

    <!-- Example to center a table in the page -->
    <div data-pdfmake-type="columns">
      <div data-pdfmake='{"width":"*"}'></div>
      <div style="width:auto">
        <table>
          <tr><th>Table</th></tr>
          <tr><td>Centered</td></tr>
        </table>
      </div>
      <div data-pdfmake='{"width":"*"}'></div>
    </div>
  2. Control page breaks using CSS classes

    master

    To trigger page breaks in your generated PDF, use a CSS class (e.g., page-break) on an element and implement a pageBreakBefore function in your PDFMake document definition. The function inspects the node's style to determine if a break should occur.

    const html = `
      <div>
        <h1>First Page</h1>
        <h1 class="page-break">Second Page</h1>
      </div>
    `;
    
    const docDefinition = {
      content: htmlToPdfmake(html),
      pageBreakBefore: function(node) {
        return node.style && node.style.includes('page-break');
      }
    };
  3. Handle images in different environments

    master

    Image support varies depending on your runtime and configuration:

    1. Node.js Environment: You must use Base64 encoded images. Standard URLs will not work in Node.

      • Example: <img src="data:image/jpeg;base64,/9j/4AAQ...">
    2. Web Browser: You can use standard image URLs.

      • Example: <img src="https://example.com/image.jpg">
      • Note: This requires the imagesByReference option.
    3. Custom Headers: For images requiring authentication, use the data-src attribute to pass a JSON object containing the URL and headers.

      • Example: <img data-src='{"url": "https://example.com/image.jpg", "headers": {"Authorization": "Bearer token"}}'>
    <!-- Best option: Base64 encoded image (Required for Node) -->
    <img src="data:image/jpeg;base64,/9j/4AAQ...">
    
    <!-- Image by URL (Only works with Web Browser + imagesByReference option) -->
    <img src="https://example.com/image.jpg">
    
    <!-- Image with custom headers -->
    <img data-src='{"url": "https://example.com/image.jpg", "headers": {"Authorization": "Bearer token"}}'>
  4. Install and use html-to-pdfmake in Node.js

    master

    For Node.js environments, you must install html-to-pdfmake and jsdom. Because the library relies on a DOM-like environment, you must initialize a JSDOM instance and pass its window object into the htmlToPdfmake options.

    Note: You must also initialize pdfMake.vfs with your fonts as per your specific pdfmake version requirements.

    npm install html-to-pdfmake jsdom
    const pdfMake = require('pdfmake/build/pdfmake');
    const pdfFonts = require('pdfmake/build/vfs_fonts');
    const htmlToPdfmake = require('html-to-pdfmake');
    const jsdom = require('jsdom');
    const { JSDOM } = jsdom;
    
    pdfMake.vfs = pdfFonts;
    
    // Initiate the "window" object for Node.js
    const { window } = new JSDOM('');
    
    const html = `
      <div>
        <h1>Sample Document</h1>
        <p>This is a <strong>simple</strong> example with <em>formatted</em> text.</p>
      </div>
    `;
    
    // Pass the window object in options
    const converted = htmlToPdfmake(html, { window });
    const docDefinition = { content: converted };
    
    // Generate PDF buffer and save to file
    pdfMake.createPdf(docDefinition).getBuffer((buffer) => {
      require('fs').writeFileSync('output.pdf', buffer);
    });
  5. Install and use html-to-pdfmake in a browser

    master

    To use html-to-pdfmake in a web browser, include the required pdfmake libraries and the html-to-pdfmake browser script via CDN. You can then call htmlToPdfmake(html) to convert an HTML string into a PDFMake-compatible format, which can be passed directly into pdfMake.createPdf().

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <!-- Include required libraries -->
      <script src="https://cdn.jsdelivr.net/npm/pdfmake@latest/build/pdfmake.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/pdfmake@latest/build/vfs_fonts.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/html-to-pdfmake/browser.js"></script>
    </head>
    <body>
      <script>
        // Convert HTML to PDFMake format
        const html = `
          <div>
            <h1>Sample Document</h1>
            <p>This is a <strong>simple</strong> example with <em>formatted</em> text.</p>
          </div>
        `;
        
        const converted = htmlToPdfmake(html);
        const docDefinition = { content: converted };
        
        // Generate PDF
        pdfMake.createPdf(docDefinition).download('document.pdf');
      </script>
    </body>
    </html>
  6. Apply custom PDFMake properties with data-pdfmake

    master

    You can pass direct PDFMake configuration objects to HTML elements using the data-pdfmake attribute. This allows you to control specific PDFMake properties that are not directly supported by standard HTML/CSS attributes, such as table widths or horizontal rule thickness.

    <!-- Custom table properties -->
    <table data-pdfmake='{"widths": [100, "*", "auto"], "heights": 40}'>
      <tr>
        <td>Fixed Width</td>
        <td>Fill Space</td>
        <td>Auto Width</td>
      </tr>
    </table>
    
    <!-- Custom HR styling -->
    <hr data-pdfmake='{"color": "red", "thickness": 2}'>
  7. Handle images by reference

    master

    When imagesByReference: true is set in the options, the library changes how <img> tags are processed. Instead of embedding the image source directly into the document definition, it returns a reference string. This is useful for managing large numbers of images or handling them via a separate collection.

    Mechanism:

    1. The library generates a unique suffix for the session.
    2. It tracks images in an internal array.
    3. The resulting object uses a reference format like img_ref_[suffix][index].
  8. Use data-pdfmake attributes for custom PDFMake properties

    master

    You can inject direct PDFMake properties into HTML elements using the data-pdfmake attribute. The library parses this attribute as JSON and applies the properties to the resulting PDFMake object.

    Example: Custom Table Layout

    <table data-pdfmake='{"layout":"noBorders"}'>
      <tr><td>Cell</td></tr>
    </table>

    Example: Custom Horizontal Rule (HR) Styles

    <hr data-pdfmake='{"thickness": 2, "color": "red"}'>
  9. Override default element styles with defaultStyles

    master

    Use the defaultStyles option to provide a mapping of HTML tags (or specific selectors) to PDFMake style objects. This ensures consistent styling across your document without needing inline CSS for every element.

    const options = {
      defaultStyles: {
        h1: { fontSize: 24, bold: true, marginBottom: 10 },
        p: { margin: [0, 5, 0, 10] },
        a: { color: 'purple', decoration: null }
      }
    };
  10. Enable automatic table sizing with tableAutoSize

    master

    Setting tableAutoSize: true enables automatic table sizing based on the content and CSS properties (like width and height) defined within the HTML table.

    const result = htmlToPdfmake(`
    <table style="width:100%">
      <tr style="height:100px">
        <td style="width:250px">Fixed width</td>
        <td>Auto width</td>
      </tr>
    </table>`, { tableAutoSize: true });
  11. Use data-pdfmake-type='columns' for PDFMake columns

    master

    To create a PDFMake columns structure, wrap your content in a <div> with the attribute data-pdfmake-type="columns".

    <div data-pdfmake-type="columns">
      <div>Column 1 content</div>
      <div>Column 2 content</div>
    </div>