DEV Community

Cover image for Convert html to pdf with a retry mechanism
Piotr Żaba
Piotr Żaba

Posted on • Edited on

Convert html to pdf with a retry mechanism

Now that you know what is HTMLeer.dev we can learn how to use it.

Get your API key

If you don't have an account, just head to Register page.
After registration go to API keys using navigation bar and create new one.

API documeentation

You can find available options in our swagger documentation.

Usage of the API

It's really simple, all you need to do is call HTMLeer API with your API key. Here's an example how you can create and download pdf file using HTMLeer API (with a help of p-retry in case of any failures).

import pRetry, { AbortError } from 'p-retry';

const generatePDF = async () => {
    const response = await fetch('https://api.htmleer.dev/v1/generate/pdf', {
        method: 'POST',
        body: JSON.stringify({
            savePdf: false,
            filename: 'my-file',
            html: `<div>Hello {{ name }}!</div>`,
            arguments: { name: 'HTMLeer' },
            options: { format: 'A4' }
        }),
        headers: {
            'content-type': 'application/json',
            'api-key': process.env.HTMLEER_API_KEY
        },
    });

    // we are stopping retrying because its custom api error
    if (!response.ok && response.status < 500) {
        throw new AbortError(response.statusText);
    }

    if (!response.ok) {
        throw new Error(response.statusText);
    }

    return response.arrayBuffer();
};

try {
    const result = await pRetry(generatePDF, { retries: 5 });
    const blob = new Blob([result], { type: "application/pdf" });
    const objectUrl = URL.createObjectURL(blob);
    window.open(objectUrl);
} catch (err) {
    console.log(err);
}
Enter fullscreen mode Exit fullscreen mode

What do you think?

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs