McAPI - HTML to PDF Converter API with Java

Java sample code to convert HTML and Website content to PDF with the McAPI HTML to PDF Converter REST API service. The sample uses Java 11 LTS but will also work with more recent versions. It will not work with Java 8 or older LTS versions. Jackson is required for building the JSON payload of the request.

Requirements: A free RapidAPI account. Replace YOUR_API_KEY in the source code below with your RapidAPI key.

All sample code below works with the free tier of the API, see the McAPI HTML to PDF API Listing for available plans.

See the overview page for a reference that lists all available parameters and error codes.

Convert an HTML Invoice to PDF in Java with HttpClient module

In this Java program, we'll convert this HTML invoice to PDF, a standard use case of HTML to PDF conversion. We set the page format to "A4". With the storeExternal option set to "true", the generated PDF will be returned as a downloadable URL (Note that PDFs sotred in the cloud will be deleted after 30 days.)

The source code:

// Java

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;

class Screenshot {

    public static void main(String[] args) throws IOException, InterruptedException {

    Map<String, Object> json = new HashMap<String, Object>();
    json.put("url", "https://mcapi.io/html2pdf/templates/invoice.html");
    json.put("format", "A4");
    json.put("storeExternal", "true");
    
    String postData = new ObjectMapper().writeValueAsString(json);

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://mcapi-html-2-pdf.p.rapidapi.com/"))
        .header("content-type", "application/json")
        .header("x-rapidapi-host", "mcapi-html-2-pdf.p.rapidapi.com")
        .header("x-rapidapi-key", "YOUR_API_KEY")
        .method("POST", HttpRequest.BodyPublishers.ofString(postData))
        .build();

    HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
    System.out.println(response.body());
}

The response will be delivered as a JSON object in response.body, e.g.:

{
  "service": "McAPI HTML 2 PDF, https://mcapi.io",
  "version": "V1",
  "pdf": "https://...pdf"
}

McAPI HTML 2 PDF API - Converted HTML Invoice as PDF with Java

The returned PDF from the Node JS request, seen here in the macOS Preview. The PDF is fully searchable:

Image of Converted HTML Invoice to PDF Java

Back to McAPI HTML to PDF API main page.