How to wait on an element before continuing the conversion

You might want to wait on something specific before generating the PDF. It could be on a chart being rendered or a dom element that must be removed (or visible) before generating the PDF.

In that case, PDFShift has a parameter called "wait_for" (https://docs.pdfshift.io/#convert-body-wait_for) that expects a String that points to a function name available globally.

PDFShift will load your page, then call this function frequently until that function returns a truthy value (could be true, a non-empty string, an integer not equal to 0, etc).

You can then implement any checks inside that function and return true only when everything is ready and available.

This works great when you want to wait on a chart to be fully rendered, or an asynchronous font that takes time to load and render, or when you want to remove a modal that appears asynchronously.

You can place your javascript function in your HTML document like this:

// This is globally available function that will be set to true 
// once the charts have been loaded
let isChartLoaded = false;
function waitForPDFShift() {
    return isChartLoaded
}

// And later on with your ApexChart code for example:

let chart = new ApexCharts(el, options);
chart.render().then(() => {
    isChartLoaded = true
})

This will generate the PDF only when the chart has been fully rendered by ApexChart.

You can also have a similar logic to wait on all the fonts to be loaded AND rendered with the following code:

let allFontsAreLoaded = false
function areFontReady () {
    return allFontsAreLoaded
}

document.fonts.ready.then(() => { allFontsAreLoaded = true })

The interesting thing here is that you can add the above javascript code directly in the "javascript" parameter of PDFShift too, which allows you to run the code by injecting the javascript.

That can be helpful if you don't have access to the HTML or can't manipulate it.

Timeout

When using "wait_for", PDFShift will wait for that function to return a truthy value, but it won't wait forever.

PDFShift have two different timeouts:

  • 30 seconds for the free accounts

  • 100 seconds for the premium accounts

These timeouts are for the whole conversion, including the duration to load and process the document, and converting to PDF.

When you use wait_for, PDFShift will first load the document, then check the remaining timeout available and wait for your function to return true up to the remaining timeout.

So for instance, a free account that loads a page that takes 10 seconds to render, will have 20 seconds available for the wait_for function before failing the conversion.

If your premium account is reaching the 100 seconds limit, you can reach out to us and ask to extend the timeout. We'll adjust your plan based on your need with a bigger timeout.

Was this helpful?