How to generate a PDF in my SaaS project?

How to generate a PDF in my SaaS project?

There are many ways to create a PDF document, all of which have advantages and disadvantages. However, for SaaS projects, one option lends itself best.

HTML to PDF

The simplest and most elegant way is to create PDF documents from HTML code. HTML is particularly suitable because of its simplicity and the ability to style content as desired.

Let's look at this simple HTML page.

<html>
  <body>
    <h1>HTML to PDF</h1>
    <p>This example uses the HTML to PDF endpoint of APIstax</p>
    <p>Visit apistax.io for more!</p>
  </body>
</html>

Pass the page as a payload to the HTML-to-PDF endpoint.

POST/v1/html-to-pdf

Using the Java client, the request might look like this:

public void htmlToPdf() {
  var content =
    """
    <html>
        <body>
            <h1>HTML to PDF</h1>
            <p>This example uses the HTML to PDF endpoint of APIstax</p>
            <p>Visit apistax.io for more!</p>
        </body>
    </html>
    """;

  var client = new APIstaxClient.Builder()
    .apiKey("API_KEY_HERE")
    .build();

  var pdf = client.convertHtmlToPdf(content);
}

Now you have a PDF document as a byte array! You can now save it, print it, send it by e-mail, and so on...

And this is what it looks like:

Generated PDF file using the APIstax HTML-to-PDF API.

Visit the HTML to PDF docs for more!

A header or footer can also be added to each document, for example if you want to display the number of pages.

To display the date at the time of generation, simply add the following code snippet to the header.

<span class="date"></span>

Or, if you want to print the current page number and the total number of pages, you can simply add the following snippet to the footer.

<span class="pageNumber"></span> of <span class="totalPages"></span>

Templates

As mentioned above, you can convert any HTML page. Simply create templates for the PDF documents you want to create, such as invoices, menus, invitations and more.