All my images are not loaded when I convert to PDF?

It can happen that when you convert your document to PDF, some images are missing.

This might be because you are using Lazy loading, where images are only displayed when the user scroll to the section of the page where the image is present.

Of course, when converting to PDF, PDFShift won't scroll your page as it's not necessary for 99% of the time, but it is when using Lazy Loading.

But rest assured, we have an easy solution for that.

All you have to do is add the following parameter when doing the conversion

"javascript": "window.scrollTo(0, document.body.scrollHeight);"

This will scroll the page from top to bottom, initiating all the images to be loaded, before making the conversion.

With that, your images will be loaded.


If you want to go a bit further in the logic, you could ensure that all the images are properly loaded prior to convert to PDF.

For that, you can use the wait_for parameter, to wait for a function to return true before continuing the conversion.

We already wrote an article about it, but we can extend the logic in this current scenario:

You can write a function that will scroll to the bottom, count the number of <img /> element, and check that the number of images loaded are the exact same as the total number of <img /> element in the page. The following script will do the trick:

function isPDFShiftReady () {
    // We scroll to the bottom to trigger all the lazy loading images
    window.scrollTo(0, document.body.scrollHeight);

    let allLoaded = true;
    // Then we check if all images are loaded
    document.querySelectorAll('img').forEach((img) => {
        if (img.complete) {
            return;
        }

        allLoaded = false;
    });

    return allLoaded;
}

You can use it by using the following parameters for PDFShift:

"javascript": "function isPDFShiftReady () {
    // We scroll to the bottom to trigger all the lazy loading images
    window.scrollTo(0, document.body.scrollHeight);

    let allLoaded = true;
    // Then we check if all images are loaded
    document.querySelectorAll('img').forEach((img) => {
        if (img.complete) {
            return;
        }

        allLoaded = false;
    });

    return allLoaded;
}",
"wait_for": "isPDFShiftReady"

This will scroll to the bottom of the page and ensure all the images are loaded before making the conversion, ensuring 100% of your images are present on the converted document!

If one of your image fails to be loaded, the function will always return false, causing the conversion to block and ultimately fail. You might need to take that into consideration in your code when calling PDFShift, or in your Javascript function to better handle failure (onerror callback).

Was this helpful?