pdfform.js

repository·master·Indexed 42 days ago

https://github.com/phihag/pdfform.js

A pure JavaScript library for filling out PDF forms in browser and server environments. Version 1.0.14 supports AcroForms and XFA-based forms using an ArrayBuffer-based workflow. It provides the transform() method to populate fields and list_fields() to discover available form fields. The library can be used with minipdf or PDF.js.

Tokens
1.4K
Snippets
5
Records
6
Agent score
3%

What's inside pdfform.js

  1. Install pdfform.js in the browser

    master

    To use pdfform.js in a browser environment, you can choose between two distribution methods:

    1. Recommended (minipdf): Download and serve pdfform.minipdf.dist.js. This uses the built-in minipdf library, which is more lightweight than PDF.js.
    2. PDF.js version: Download and serve pdfform.pdf_js.dist.js if you require the full capabilities of PDF.js.

    Alternatively, you can manually include the source files from the repository by adding minipdf.js and pdfform.js to your project. If you choose the manual route, you must also include the pako library as a dependency.

    <!-- Recommended: download from https://raw.githubusercontent.com/phihag/pdfform.js/dist/dist/pdfform.minipdf.dist.js -->
    <script src="downloaded/pdfform.minipdf.dist.js"></script>
  2. Initialize pdfform.js with a PDF library

    master

    The pdfform(minipdf_lib) factory function initializes the library. It requires a PDF manipulation library (like minipdf) to handle the underlying PDF structure.

    Initialization Options

    • Explicit Library: Pass a library instance directly: pdfform(myMinipdfLib).
    • pdf.js Compatibility: Passing 'pdf.js' as the argument will load the ./minipdf_js.js adapter.
    • Autodetect: If no argument is provided, the library attempts to autodetect available libraries in the following order:
      1. Global minipdf_js object.
      2. Global minipdf object.
      3. Requiring ./minipdf.js (Node.js environment).

    Note: In Node.js environments, the library automatically loads compatibility modules for xmldom, text-encoding, and pako if they are required.

    const pdfform = require('pdfform.js');
    // If minipdf is already in your environment, you can just call:
    const api = pdfform();
  3. List available PDF form fields with list_fields()

    master
    If you need to discover the names and types of the fields available within a specific PDF, use the list_fields function. This is useful for mapping your data to the correct PDF keys.
  4. Fill out PDF forms using transform()

    master

    The primary way to populate a PDF form is by calling the transform method on the pdfform() instance.

    Parameters:

    • pdf_buf: An ArrayBuffer containing the original PDF file contents.
    • fields: An object where keys are the field names and values are arrays of strings representing the values to be inserted into those fields.

    Returns:

    • An ArrayBuffer containing the resulting PDF file with the fields filled.
    var pdf_buf = ...; // load PDF into an ArrayBuffer
    var fields = {
        'fieldname': ['value for fieldname[0]', 'value for fieldname[1]'],
    };
    var out_buf = pdfform().transform(pdf_buf, fields);
    // out_buf contains the resulting PDF file
  5. Inspect PDF form fields with list_fields()

    master

    The list_fields(data) function parses a PDF buffer and returns an object describing all available form fields. This is useful for discovering the exact keys needed for the transform() function.

    Return Value Structure

    The returned object uses field names as keys. If a field uses array-based indexing (like radio buttons), the key is the base name, and the value is an array where the index corresponds to the field index.

    Supported Field Types in Output:

    • { type: 'string' } (for Tx fields)
    • { type: 'boolean' } (for Btn fields)
    • { type: 'select', options: [...] } (for Ch fields)
    • { type: 'radio', options: [...] } (for radio button groups)
    const fields = pdfform().list_fields(pdfBuffer);
    console.log(fields);
    // Output might look like:
    // {
    //   'FirstName': [{ type: 'string' }],
    //   'Gender': [{ type: 'radio', options: ['Male', 'Female'] }]
    // }
  6. Fill PDF forms using transform()

    master

    The transform(buf, fields) function takes a PDF file buffer and a mapping of field names to values, returning a new buffer containing the filled PDF. It supports both AcroForms and XFA-based forms.

    Field Mapping Formats

    1. AcroForms:

      • Text Fields (Tx): Map a string to the field.
      • Checkboxes/Buttons (Btn): Map a boolean to the field. true sets the field to Yes, false sets it to Off.
      • Choice/Dropdowns (Ch): Map a string to the selected option.
      • Radio Buttons: Handled via the field name syntax name[index]. For example, if a radio group is named Gender, you can set the selection using {'Gender[0]': 'Male'}.
    2. XFA Forms:

      • XFA fields are updated by matching the key in the fields object to XML tags within the XFA data stream. Values are injected as text nodes. Booleans are converted to 1 or 0.
    // Example: Filling an AcroForm
    const filledBuf = pdfform().transform(originalPdfBuf, {
      'FirstName': 'John',
      'IsSubscriber': true,
      'Gender[0]': 'Male' // Selecting the first option in a radio group
    });