# Zapier Integration: Automate Document Generation


The PDFMonkey Zapier integration lets you generate, retrieve, and manage documents directly from your Zaps. If you are new to the integration, start with the [Getting Started](#getting-started) section below for a complete end-to-end tutorial.

## Getting Started {#getting-started}

<iframe width="100%" height="400" src="https://www.youtube.com/embed/yLMBYxehDMg" title="YouTube video player" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen></iframe>

Before you begin, make sure you have a PDFMonkey account and a published template. See [From Zero to First Document](../getting-started/from-zero-to-first-document.md) for setup instructions.

### Writing Your First Template

In the **HTML** tab of your template, insert the following code:

```liquid title="HTML"
<p class="greeting">Hello {{name}}!</p>
<p>Your favorite number is {{favoriteNumber}}.</p>
```

In the **CSS** tab, insert the following code:

```css
.greeting {
  color: #6d28d9;
  font-size: 24px;
}
```

And finally in the **Test data** tab, insert this:

```json
{
  "name": "Peter Parker",
  "favoriteNumber": 8
}
```

Click **Save** to see the preview update, then click **Publish** to make the template available for generation.

> [!WARNING]
> **Always publish your template!**
>
> Forgetting to publish your template is a frequent mistake, especially when switching back and forth between Zapier and PDFMonkey. If the documents you generate don't match your template, always check you published it.


### Generating Your First Document

Now that your template is complete, let's head to Zapier.

For this guide we will define a Zap triggered by a form submission on [Tally](https://tally.so/), generate a document in PDFMonkey, and then send it by email.

#### The Tally Form

We will use the following Tally form as our source of information in our Zap:

![Tally form used as Zap trigger](../img/zapier-guide-select-pdfmonkey.webp)

#### Setting Up Your Zap

Start by creating a new Zap. As trigger we will use Tally's **New Response** event:

![Creating a new Zap with Tally trigger](../img/zapier-guide-create-document.webp)

We then proceed to fill out our form and check it's correctly connected in Zapier:

![Selecting the PDFMonkey template](../img/zapier-guide-select-template.webp)

![Connecting your PDFMonkey account](../img/zapier-guide-connect-account.webp)

#### Calling PDFMonkey

Now that we have some data to work with, we will configure our PDFMonkey action.

Select the PDFMonkey app and choose the **Generate Document** action.

![Mapping fields in the PDFMonkey action](../img/zapier-guide-map-fields.webp)

You can then map the data from the form to variables for your document. Make sure to use the same names as the ones used when writing the template.

![Testing the PDFMonkey action](../img/zapier-guide-test-action.webp)

> [!NOTE]
> **Naming variables**
>
> If you're wondering how to write proper names so it works in PDFMonkey, we provide [a list of correct/incorrect variable name formats](../code-templates/defining-dynamic-data.md#naming-your-variables).


We're now ready to test the document generation.

![Document successfully created](../img/zapier-guide-document-created.webp)

![Downloading the generated document](../img/zapier-guide-download-pdf.webp)

#### Sending the Document by Email

Now that our document is generated, let's send it by email.

Add a new action and select the Email by Zapier app, then choose the **Send Outbound Email** action.

![Configuring the send email action](../img/zapier-guide-send-email.webp)

We can now use our document's **Download URL** as attachment for the email. Zapier automatically downloads the file and attaches it.

![The complete Zap from trigger to email](../img/zapier-guide-final-zap.webp)

You can now test this last action and you should receive an email with the document attached.

Congrats! You generated your very first PDFMonkey document using Zapier!

## Generate a Document {#generate-a-document}

The **Generate Document** action creates a document from one of your PDFMonkey templates. You select a template, map your data fields, and PDFMonkey generates the document. The action returns a [download URL](../generating-documents/download-url.md) you can use in subsequent Zap steps.

For a step-by-step walkthrough of your first Zap, see the [Getting Started](#getting-started) section above.

### Advanced JSON Payload {#advanced-json}

> [!WARNING]
> **Be careful!**
>
> With great power comes great trouble sometimes. Only switch to advanced JSON if you know what you are doing and know how to escape your data properly.
> 
> See [Troubleshooting](#troubleshooting) for more information.


By default, the integration provides a simple mapping field to define what gets sent to PDFMonkey. In most cases the simple mapping is sufficient, but there are situations where you need to structure your data differently. The **Use a custom JSON structure** option switches from the simple mapping to a text area where you can insert your own JSON with nested properties:

![Custom JSON payload option in the PDFMonkey Zapier action](../img/zapier-custom-json-payload.webp)

### Custom Filename {#custom-filename}

You can specify a custom name for the generated file. This is useful if you plan on storing the document in a service like Drive or Dropbox.

You can use dynamic parts to build the filename, but keep these restrictions in mind:

- The filename must not contain any slash `/` or backslash `\`
- Non-latin characters should be avoided as they can be corrupted when saving the file

Short names based on dates or IDs tend to work best.

> [!TIP]
> For more details on filename options (including setting filenames via the API), see [Custom Filename](../generating-documents/custom-filename.md).


### Metadata {#metadata}

When you generate a document, you can attach metadata to it. Metadata is not available in the template and cannot influence the content of the document; it is simply attached to it.

A common use case is receiving the document via a [webhook](../generating-documents/webhooks.md) and using its metadata to route or handle it differently.

![Metadata fields in the PDFMonkey Zapier action](../img/zapier-metadata-fields.webp)

### Line Items {#line-items}

If you are generating an invoice or a quote, you will likely need to deal with line items. Zapier provides a way to access those items if the trigger you use supports them.

Take the example of a Stripe invoice. Items in the invoice are available through a Line Items collection. To send those items in a way that PDFMonkey can understand, set **Add Line Items** to **Yes**.

This opens a section where you specify what a **single item** looks like. For example, consider a Stripe invoice with these items:

```
Delicious waffle         3.50€      x12      = 42.00€
Perfectly round donut    4.99€      x5       = 24.95€
TOTAL                                          66.95€
```

The `TOTAL` should be sent as basic data for the document, while the name, unit price, quantity, and total amount for each item should be sent as line items from Zapier:

![Line items mapping in the PDFMonkey Zapier action](../img/zapier-line-items-mapping.webp)

> [!TIP]
> **Mapping or JSON**
>
> The field to define the data for a line item uses the same form as the main data. If you use [advanced JSON](#advanced-json) for the main data, the line item payload is also defined using advanced JSON.


#### Using the Line Items in Your Template

When Zapier sends the line items to PDFMonkey, they are accessible through a special `lineItems` variable. In the example above, the payload would look like this:

```json title="JSON"
{
  "lineItems": [
    {
      "product": "Delicious waffle",
      "quantity": "12",
      "unitPrice": "3.50",
      "totalAmount": "42.00"
    },
    {
      "product": "Perfectly round donut",
      "quantity": "5",
      "unitPrice": "4.99",
      "totalAmount": "24.95"
    }
  ]
}
```

> [!NOTE]
> **Only strings attached**
>
> If you look closely at the payload above, only strings are sent. Zapier does not differentiate between text and numbers.
> 
> Luckily, Liquid (the template language we use) is smart enough to convert those values to numbers when you do math with them. Just keep this in mind if you run into trouble with numbers. See [How to Do Maths](../code-templates/how-to-do-maths.md) for arithmetic tips.


You can loop over the `lineItems` array to display content for each item individually:

```liquid title="HTML"
{% for item in lineItems %}
  <p>{{item.product}} at {{item.unitPrice}}€ x{{item.quantity}} = {{item.totalAmount}}€</p>
{% endfor %}
```

This produces the following HTML:

```html title="HTML"
<p>Delicious waffle at 3.50€ x12 = 42.00€</p>
<p>Perfectly round donut at 4.99€ x5 = 24.95€</p>
```

You will probably want to build a table row for each item, but this gives you a good idea of how to get started. See [Conditions and Loops](../code-templates/conditions-and-loops.md) for more Liquid loop techniques.

## Document Generated Trigger {#document-generated-trigger}

The **Document Generated** trigger fires your Zap every time a document finishes generating (reaches the `success` [status](../generating-documents/document-statuses.md)). This is useful for automating post-generation tasks like storing the file in Dropbox, sending it by email, or logging it in a spreadsheet.

![Selecting the Document Generated event in Zapier](../img/zapier-trigger-select-event.webp)

You can choose to trigger your Zap for:

- Any template in your workspace
- A single template
- Several specific templates

![Connecting your PDFMonkey account in the trigger](../img/zapier-trigger-connect-account.webp)

Make sure to have at least one generated document before testing your trigger in Zapier.

![Selecting which template to trigger on](../img/zapier-trigger-select-template.webp)

You can then use the generated file to store it, send it by email, or get notified in some way.

> [!NOTE]
> **Leveraging metadata**
>
> The document exposed by the trigger does not contain your payload. If you need any information in the following actions, we recommend [attaching metadata](#metadata) to the document.
> 
> That is what we did with the Tally information in this example.


![Test result showing the trigger output](../img/zapier-trigger-test-result.webp)

## Find and Delete Documents {#retrieve-and-delete}

### Find a Document {#retrieve-a-document}

The **Find Document** search fetches a previously generated document from its **Document ID**. Use this when you need to access a document's details or [download URL](../generating-documents/download-url.md) in a later step of your Zap; for example, after a delay or in a separate workflow from the one that generated it.

### Delete a Document

The **Delete Document** action removes a single document from PDFMonkey. Use this to clean up documents after you have processed them; for example, after downloading and storing the file elsewhere. See [Retention and Deletion](../generating-documents/retention-and-deletion.md) for more on document lifecycle management.

## Troubleshooting {#troubleshooting}

### Download URL Expired {#download-url-expired}

If you get an expired download URL error while building your Zap, reload the example record in your trigger.

The [download URL](../generating-documents/download-url.md) is only valid for 1 hour. You need to refresh the documents in Zapier to get a new URL. Click the **Load More** button in the Test section of your trigger:

![Refreshing trigger fields to get a new download URL](../img/zapier-refresh-trigger-fields.webp)

> [!NOTE]
> **Generation output**
>
> This tip applies to the trigger only. For the output of a Generate Document action, you need to generate a new document to get fresh data and a valid download URL.


> [!TIP]
> If your Zaps fail because the URL has expired by the time a later step runs, see [Download URL Returns 403](../troubleshooting/download-url-gives-403.md) for solutions.


### 422 Responses {#422-responses}

This error usually happens when you use the custom JSON option and have values that need escaping before being sent to PDFMonkey.

#### Values Containing Double Quotes

Consider the following custom JSON:

```json5 title="Custom JSON"
{
  user: {
    name: "(Dynamic Field From Zapier)",
  },
}
```

If the value in `Dynamic Field From Zapier` contains quotes, the resulting JSON breaks. Take `Peter "Spiderman" Parker` as an example:

```json title="Invalid JSON"
{
  "user": {
    "name": "Peter "Spiderman" Parker"
  }
}
```

This is not valid JSON. What you need is to _escape_ the double quotes:

```json title="Valid JSON"
{
  "user": {
    "name": "Peter \"Spiderman\" Parker"
  }
}
```

> [!NOTE]
> **HTML attributes**
>
> If you send HTML, this happens frequently since attributes almost always use double quotes (e.g., `<div class="test">`).


#### Values Containing Line Breaks

JSON does not support values that include raw line breaks:

```json title="Invalid JSON"
{
  "userBio": "Once upon a time,
They lived happily ever after."
}
```

Escape the line breaks by replacing them with a `<br />` tag or using the text representation `\n`:

```json title="Valid JSON"
{
  "userBio": "Once upon a time,\nThey lived happily ever after."
}
```

#### Solution {#escaping-solution}

> [!NOTE]
> **Do you really need custom JSON?**
>
> The first question to ask yourself is whether you truly need custom JSON. In most cases the simple mapping approach is sufficient and takes care of escaping automatically.


If you cannot escape the values before they reach Zapier, add a **Code by Zapier** action before calling PDFMonkey.

Suppose your data contains both line breaks and double quotes:

| Item                           | Value                                                                                                                                                                                    |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Trigger App User Bio**       | <p>This is the bio of the user.</p><p>It's a free form text that the user can edit so it can contain line breaks.</p><p><br />It could even be split in a few paragraphs... why not?</p> |
| **Trigger App User Name**      | Peter Parker                                                                                                                                                                             |
| **Trigger App User Full Name** | Peter "Spiderman" Parker                                                                                                                                                                 |

You need to escape values for both `Trigger App User Bio` and `Trigger App User Full Name`. Start by adding a **Code by Zapier** action to your Zap and selecting **Run Javascript**:

![Adding a Code by Zapier action with raw input data](../img/zapier-error-422-raw-body.webp)

Give your fields names that help identify them in the following steps:

![Naming the input fields in Code by Zapier](../img/zapier-error-422-json-format.webp)

Now add the code that escapes the values:

```javascript title="Code by Zapier"
let data = Object.assign({}, inputData);

for (let key in data) {
  if (typeof data[key] === "string" && data[key].length > 0) {
    data[key] = data[key].replace(/\r?\n/g, "<br>").replace(/\t/g, " ").replace(/"/g, '\\\"');
  }
}

output = [data];
```

This gives you the same fields in the output but with their values properly escaped:

![The escaped output from Code by Zapier](../img/zapier-error-422-custom-request.webp)

You can now use those values when building your PDFMonkey payload:

![Using the escaped values in the PDFMonkey action](../img/zapier-error-422-fixed-payload.webp)

Notice how we used the fields from the Code by Zapier step, not from the trigger directly.

## Next Steps {#next-steps}

- [From Zero to First Document](../getting-started/from-zero-to-first-document.md): Set up your PDFMonkey account and create your first template
- [Defining Dynamic Data](../code-templates/defining-dynamic-data.md): Learn how to structure the JSON payload for your templates
- [Document Statuses](../generating-documents/document-statuses.md): Understand the lifecycle of a generated document
- [Webhooks](../generating-documents/webhooks.md): Receive real-time notifications when documents finish generating
- Explore other integrations: [Make](./make.md), [n8n](./n8n.md), [Workato](./workato.md)
