npm package: @finum/html-to-pdf-to-sign
Description: A library for converting HTML to PDF and identifying signature locations. It simplifies document generation, provides support for marking and locating signing areas, and integrates with APIs like Documenso. Designed for use in both local and serverless en
Author: FiNUM
Latest version: 0.1.1

# HTML to PDF and Sign Locations Library

This library provides functionality to convert HTML to PDF and find sign locations within a PDF document. It is designed to work both locally and in serverless environments.

## Features

- Convert HTML strings to PDFs
- Mark sign locations in HTML
- Find these areas in generated PDF data
- Convert sign locations to different coordinate systems
- [Documenso](https://documenso.com/) API functionality

## Motivation

Even though most business has moved to the digital realm, signing documents by hand or digitally is still an integral part of many areas. However, creating documents with context-specific data can be challenging as PDF editing is notoriously difficult. This can be addressed by generating entire PDF documents from HTML. However, the lack of direct native signature support (Adobe or otherwise) in HTML makes interfacing these documents with digital signature providers difficult.

This library was created to solve this problem by extracting the PDF coordinates of predefined areas in HTML. As many signature services can work with PDF coordinates, this makes interfacing with them significantly easier.

## Getting Started

1. Install the package:

  ```bash
  npm i @finum/html-to-pdf-to-sign
  ```

2. Generate a PDF and write it to a file:

  ```js
  import { htmlToPdf } from '@finum/html-to-pdf-to-sign/all.js';

  const pdfBuffer = await htmlToPdf({ html: '<h1>Hello, World!</h1>' });
  await writeFile(new URL('./example.pdf', import.meta.url), pdfBuffer);
  ```

3. Add signing locations using a special placeholder:

  ```js
  import {
    htmlToPdf,
    getSignLocations,
    SIGN1_BASE64_IMAGE,
  } from '@finum/html-to-pdf-to-sign/all.js';

  const pdfBuffer = await htmlToPdf({
    html: `
    <h1>Hello, World!</h1>
    <p>Sign Below</p>
    <img
      src="${SIGN1_BASE64_IMAGE}"
      width="200px"
      height="200px"
    />
   `,
  });
  ```

4. Get all sign locations and use them to create signatures, for example with [Documenso](https://documenso.com/):

  ```js
  import { getSignLocationsDocumenso } from '@finum/html-to-pdf-to-sign/all.js';

  const recipients = [{ id: 'foo' }, { id: 'bar' }];

  // Example for Documenso
  await fetch(`${endpoint}/api/v1/documents/${documentId}/fields`, {
    method: 'POST',
    headers: { Authorization: token, 'Content-Type': 'application/json' },
    body: JSON.stringify(await getSignLocationsDocumenso(pdfBuffer, recipients)),
  });
  ```

5. Integrate with your own signature provider:

  ```js
  import { getSignLocations, signLocationsToDocumenso } from '@finum/html-to-pdf-to-sign/all.js';

  const signLocations = await getSignLocations(pdfBuffer, {
    targetBasis: 'percent-top-left',
    pageIndexStart: 1,
  });
  console.log(signLocations);
  const recipients = [{ id: 'foo' }, { id: 'bar' }];

  // Example Documenso manual
  await fetch(`${endpoint}/api/v1/documents/${documentId}/fields`, {
    method: 'POST',
    headers: { Authorization: token, 'Content-Type': 'application/json' },
    body: JSON.stringify(
    signLocations.map(({ x, y, height, width, ref, page }) => ({
      page,
      recipient: recipients[ref],
      pageX: x,
      pageY: y,
      pageHeight: height,
      pageWidth: width
    }))
    ),
  });
  ```

### htmlToPdf.js

This file contains functions to generate a PDF document from HTML.

#### `htmlToPdf(options)`

- **Parameters:**
  - `options` (Object): Configuration options for the conversion.
   - `html` (string): The HTML content to convert. Defaults to `'Please provide your own HTML'`.

- **Returns:**
  - A Promise that resolves to a Buffer containing the generated PDF.

- **Usage:**

  ```javascript
  import { htmlToPdf } from '@finum/html-to-pdf-to-sign/all.js';

  const pdfBuffer = await htmlToPdf({ html: '<h1>Hello, World!</h1>' });
  ```

### getSignLocations.js

This file contains functions to find sign locations within a PDF document.

#### `getSignLocations(pdfData, options)`

- **Parameters:**
  - `pdfData` (Uint8Array | Buffer): The PDF data.
  - `options` (Object): Configuration options for finding sign locations.
   - `targetBasis` (string): The basis for target coordinates. Can be `'pt'`, `'percent-top-left'`, or `'percent-bottom-left'`. Defaults to `'pt'`.
   - `pageIndexStart` (number): The starting page index. Defaults to `0`.

- **Returns:**
  - A Promise that resolves to an array of sign locations.

- **Usage:**

  ```javascript
  import { getSignLocations } from '@finum/html-to-pdf-to-sign/all.js';

  const signLocations = await getSignLocations(pdfBuffer, { targetBasis: 'percent-top-left' });
  ```

### getSignLocationsDocumenso.js

This file contains functions to find sign locations within a PDF document.

#### `getSignLocationsDocumenso(pdfData, recipients)`

- **Parameters:**
  - `pdfData` (Uint8Array | Buffer): The PDF data.
  - `recipients` (Array<{id: string}>): Array containing Documenso recipients. The ordering of recipients corresponds to sign location IDs, e.g., `[{id: 'foo'}, {id: 'bar'}]` => `foo` signs `SIGN1` locations, `bar` signs `SIGN2` locations. **Currently only supports one recipient!**

- **Returns:**
  - A Promise that resolves to an array of Documenso sign locations.

- **Usage:**

  ```javascript
  import { getSignLocationsDocumenso } from '@finum/html-to-pdf-to-sign/all.js';

  const signLocations = await getSignLocationsDocumenso(pdfBuffer, [{ id: 'foo' }, { id: 'bar' }]);
  ```

## Having Issues?

Open an issue on [GitHub](https://github.com/FinumAt/devkit/issues)