Generating PDFs from JSON in MuleSoft: A Reusable Enterprise Pattern

Generating PDFs from JSON in MuleSoft: A Reusable Enterprise Pattern

Overview

This document describes a generic and reusable MuleSoft implementation for generating a PDF document from JSON data. The solution uses:

  • Parse Template component to transform JSON payloads into an HTML document
  • A custom Java class to convert HTML into PDF
  • File Write connector to persist the generated PDF

This pattern can be reused for invoices, order confirmations, reports, statements, or any document-style output.

High-Level Flow

  1. Client sends a JSON payload (e.g., Order + Customer details)
  2. Mule parses the JSON into an HTML template using Parse Template
  3. Generated HTML is passed to a custom Java class
  4. Java class converts HTML → PDF
  5. Mule sets the correct MIME type (application/pdf)
  6. PDF file is written to a configured location

Sample Input JSON

{
  "order": {
    "orderId": "ORD-1000456",
    "orderDate": "2025-01-15T10:30:00Z",
    "orderStatus": "CONFIRMED",
    "currency": "GBP",
    "totalAmount": 1250.75,
    "items": [
      {
        "itemId": "ITEM-001",
        "productCode": "PS.MFM",
        "productName": "Material Flow Manager",
        "quantity": 2,
        "unitPrice": 450.00,
        "lineAmount": 900.00
      }
    ],
    "payment": {
      "paymentMethod": "CREDIT_CARD",
      "paymentStatus": "PAID",
      "transactionId": "TXN-789654123"
    }
  },
  "customer": {
    "customerId": "CUST-90876",
    "name": {
      "firstName": "John",
      "lastName": "Smith"
    },
    "companyName": "Acme Corporation",
    "contact": {
      "email": "john.smith@acmecorp.com",
      "phone": "+44-7700-900123"
    }
  }
}        

HTML Template (Parse Template)

The HTML template is stored under src/main/resources/html/ and uses DataWeave expressions to bind JSON values. The HTML template is based on the business requirement

Key characteristics:

  • Inline CSS for consistent PDF styling
  • DataWeave expressions (#[output text --- ]) to inject values
  • Dynamic table rendering using map and joinBy

Article content
Article content

Sample Snippet (Dynamic table rendering)

#[output text --- (payload.order.items map (item) ->
'
<tr>
<td>' ++ item.itemId ++ '</td>
<td>' ++ item.productCode ++ '</td>
<td>' ++ item.productName ++ '</td>
<td>' ++ item.quantity ++ '</td>
<td>' ++ item.unitPrice ++ '</td>
<td>' ++ item.lineAmount ++ '</td>
</tr>
') joinBy ""]        

Parse Template Configuration

<parse-template
    doc:name="Parse Template"
    outputMimeType="text/html"
    location="html/order.template" />        

Outcome: JSON payload → fully rendered HTML document

Custom Java Class – HTML to PDF Conversion

A reusable Java utility converts HTML into PDF using iText HTML2PDF dependency.

Responsibilities

  • Accept HTML as String
  • Convert to PDF byte array
  • Set A4 page size

iTextHTML2PDF dependency

Add this dependency to the pom file of the project

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>html2pdf</artifactId>
    <version>5.0.5</version>
</dependency>        

Java Implementation

Create new package under src/main/java and keep the custom java class there

Article content

Java Class using iTextHTML2PDF dependency

public class HtmltoPdf {
    public static byte[] convertHtmlToPdf(String html) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ConverterProperties converterProperties = new ConverterProperties();
        PdfWriter writer = new PdfWriter(outputStream);
        PdfDocument pdf = new PdfDocument(writer);
        pdf.setDefaultPageSize(PageSize.A4);
        HtmlConverter.convertToPdf(html, pdf, converterProperties);
        pdf.close();
        return outputStream.toByteArray();
    }
}        

DataWeave Transformation – HTML to PDF

This transformation is used to execute the Java class to convert HTML string into PDF byte

import java!pdfcreate::HtmltoPdf
output application/java
---
HtmltoPdf::convertHtmlToPdf(payload)        

Input: HTML string Output: PDF as byte[]

Setting MIME Type

After conversion, the payload is explicitly marked as a PDF using Set Payload component with Mime Type as application/pdf

<set-payload
    value="#[payload]"
    mimeType="application/pdf"
    doc:name="Changing MIME Type as application/pdf" />        

Writing PDF to File System

The file can be saved in the local folder using File Write Component. To extend this it can be stored in S3 Bucket, Azure Blob or Salesforce

<file:write
    doc:name="Write"
    path="/target/output/order.pdf" />        
Article content

Reusability & Extension

This implementation can be reused for:

  • Invoice generation
  • Statements and reports
  • Shipping labels
  • Notifications and confirmations

To extend:

  • Add multiple templates
  • Parameterize file name and location
  • Store PDF in S3 / Azure Blob / Salesforce
  • Return PDF as HTTP response

Key Benefits

  • Clean separation of data, presentation, and document generation
  • Template-driven and business-friendly
  • Reusable Java utility
  • Works consistently across environments

Conclusion

This approach provides a robust, extensible, and production-ready solution for generating PDFs in MuleSoft by combining Parse Template, DataWeave, and a custom Java class. It is suitable for enterprise-scale document generation use cases.



Thanks a lot. This is very insightful ✨

To view or add a comment, sign in

More articles by MuleCraft Digital

Others also viewed

Explore content categories