Help

PDF Generation Directly in Airtable with DynamicDocs API

3378 3
cancel
Showing results for 
Search instead for 
Did you mean: 
Igrod
4 - Data Explorer
4 - Data Explorer

This article shows how to generate a PDF based on one of the DynamicDocs JSON to PDF templates from Airtable. PDF generation is done by setting up a script which can be prompted with a button. The script creates a JSON with underlying data from Airtable and uses DynamicDocs API to generate the PDF. The PDF is then downloaded and put into the Airtable attachment field.

 

What is DynamicDocs API?

DynamicDocs API is JSON to PDF API based on LaTeX that allows users to generate dynamic PDF documents in a matter of seconds. PDF generation happens with LaTeX, a mark-up style language that separates formatting and content. LaTeX consistently applies a user-defined style throughout the documents and has become very popular in academic circles due to its ability to create high-quality, complex documents. The templates utilise special commands that can create dynamic text with logic statements, tables spanning multiple pages, great-looking headers & footers and custom charts based on the underlying data. 

 

What is JSON to PDF?

JSON to PDF is a technology that allows users to convert a JSON file (which stands for JavaScript Object Notation) into a PDF document. JSON is a common data format that is often used for storing and transmitting data, especially in web applications and APIs. DynamicDocs API offers a library of ready-made JSON to PDF endpoints. They do not require any knowledge of LaTeX (DynamicDocs is a PDF API based on LaTeX) as its content and format are completely controlled by the JSON. For the purpose of this tutorial, the QR Code v1 JSON to PDF template will be used, which creates a PDF with QR code and caption in the following format.

qr-code-v1.pngCreate PDFs in Airtable with the Scripting Extension

To get started, we created the following table in Airtable with the data we need to generate a QR code:airtable-table.png

Notice the Button And Attachment fields (named Generate QR Code and PDF Attachment, respectively) which will be used to run the script and save the generated PDF file in the Airtable directly. To make API calls to DynamicDocs API, we will need to Add an Airtable Extension called Scripting. Scripting is used to write Javascript code to perform repeatable tasks. In our case, we will use it to format the JSON payload and call the DynamicDocs API. To authenticate the API calls, we require the DynamicDocs API-Key (Adv-Security-Token as a header parameter), which is generated in your account's dashboard on advicement.io. Each account is given a Free plan with a limited number of monthly API calls. For more information on authentication and calling the API, please consult DynamicDocs API documentation.

airtable-scripting.png

 

Save the Generated PDF in the Attachment Field

Once we obtained the DynamicDocs API-Key and activated the Scripting extension, we added the following code to the script named 'Create QR Code PDF with DynamicDocs API'. 

 

const API_KEY = 'YOUR-API-KEY-HERE'
const TEMPLATE_TOKEN = 'pub-qr-code-v1'

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
};

let currentTable = base.getTable("QR Codes")
let record = await input.recordAsync('Pick a record', currentTable)

let caption = record.getCellValueAsString('Caption')
let url = record.getCellValueAsString('URL').replace(/,/g, '').trim()

var data = {
        "documentSettings": {
            "pageHEXColour": "FFFFFF",
            "qrCodeHEXColour": "0049B7",
            "textHEXColour": "222222",
            "font": "open sans",
            "qrCodeHeight": "6cm",
            "documentHeight": "9cm",
            "documentWidth": "8cm"
        },
        "documentContent": {
            "caption": caption,
            "url": url
        }
    };


// output.text(`JSON: ${JSON.stringify(data)}`);

let response1 = await remoteFetchAsync(`https://api.advicement.io/v1/templates/${TEMPLATE_TOKEN}/compile`, {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
        'Content-Type' : 'application/json',
        'Adv-Security-Token' : `${API_KEY}`
    }
});

let documentStatus = await response1.json();

const  documentStatusUrl = documentStatus.documentStatusUrl;

const maxNumberOfTries = 60; // your max number of tries
const sleepBetweenTries = 10000; // your interval between attempts
let tries = 1;

let response2 = await remoteFetchAsync(documentStatusUrl, {
method: 'GET',  
});

var statusJson = await response2.json();

while ((statusJson.statusCode == 102) && (tries < maxNumberOfTries)) {     
    tries = tries + 1;
    await timeout(sleepBetweenTries);
    
    let response2 = await remoteFetchAsync(documentStatusUrl, {
        method: 'GET',  
    });

    statusJson = await response2.json();

};

if (statusJson.statusCode == "201") {

    await currentTable.updateRecordAsync(record.id, {'PDF Attachment': [{url:statusJson.documentUrl, filename: 'QR Code'}]})
    output.text(`Your PDF document is ready!`);
    
} else {
    output.text(`Unable to download the document after ${tries} tries.\n API response is ${JSON.stringify(statusJson)}`);
};

 

Now Airtable may automatically link the newly created button field with the script above. Alternatively, you can do so by opening the Button field options and selecting your script:

airtable-button-field.png

Now we can simply click the button in each record and wait a couple seconds while the PDF appears in the Attachment field.

airtable-table-with-pdf.png

 

PDF Generation Script Explained

For more interested readers, we provide a full explanation of the script above in the PDF Generation Directly in Airtable with DynamicDocs API article on the ADVICEment blog.

 

Final Remarks

The code above can easily be adapted to different fields and used to generate different PDF types. Visit JSON to PDF template page for a list of available ready-made templates from DynamicDocs API. Alternatively, visit DynamicDocs API on the Postman API network for API call examples in other computer languages.

3 Replies 3

This looks like an interesting document generation technique, especially when people need formatting features that are difficult to accomplish with HTML/CSS. Are you associated with DynamicDocs ?

Can you share more about your LaTeX document templates? How does one go about creating a custom template on your system? What resources do you recommend for learning the LaTeX syntax?

By the way, I recommend adjusting your script so that you include the .pdf file extension with your filename when you upload the file to Airtable.

Hi @kuovonne

Thank you for your comment and suggestion. Yes, I am associated with DynamicDocs API. 
Using LaTeX API for PDF generation does give users another option for PDF generation. We have been building LaTeX templates for a while and our clients are always impressed with the quality of the documents produced. We are currently growing our library of LaTeX templates and JSON to PDF templates (these templates do not require any knowledge of LaTeX from users as the content is controlled by the JSON payload). You can learn more about creating your own LaTeX templates using our DynamicDocs documentation and Merge JSON to PDF page. Here is also a list of our favourite LaTeX resources: 

Hope this helps. Let us know if you have any further queries. 🙂 

typeflow
5 - Automation Enthusiast
5 - Automation Enthusiast

If you're looking for an alternative solution, Typeflow can help you quickly generate PDFs from Airtable data using Google Docs templates. It's straightforward and efficient.

Feel free to give it a try, and I'd love to hear your feedback! I'm also offering a lifetime plan for early users at just $100. Ping me if you're interested or have any questions.