How to Convert HTML to PDF with Java
Why Convert HTML to PDF with Java?
The pdfRest Convert to PDF API Tool provides a seamless way to convert HTML files into PDF documents using Java. This tutorial will guide you through the process of sending an API call to convert HTML to PDF using Java. By leveraging this API, developers can integrate HTML-to-PDF conversion capabilities into their Java applications, enhancing functionality and improving user experience.
For example, a business might need to convert dynamically generated HTML reports or web pages into PDFs for standardized document handling and storage. Using this API, you can automate the conversion of HTML files to PDF, ensuring all documents are in a consistent format for archiving, sharing, or distribution to clients and partners.
Convert HTML to PDF with Java Code Example
import io.github.cdimascio.dotenv.Dotenv; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.*; import org.json.JSONObject; public class PDF { // Specify the path to your HTML file here, or as the first argument when running the program. private static final String DEFAULT_FILE_PATH = "/path/to/file.html"; // Specify your API key here, or in the environment variable PDFREST_API_KEY. // You can also put the environment variable in a .env file. private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; public static void main(String[] args) { File inputFile; if (args.length > 0) { inputFile = new File(args[0]); } else { inputFile = new File(DEFAULT_FILE_PATH); } final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load(); final RequestBody inputFileRequestBody = RequestBody.create(inputFile, MediaType.parse("text/html")); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", inputFile.getName(), inputFileRequestBody) .addFormDataPart("output", "pdfrest_pdf") .build(); Request request = new Request.Builder() .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY)) .url("https://api.pdfrest.com/pdf") .post(requestBody) .build(); try { OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build(); Response response = client.newCall(request).execute(); System.out.println("Result code " + response.code()); if (response.body() != null) { System.out.println(prettyJson(response.body().string())); } } catch (IOException e) { throw new RuntimeException(e); } } private static String prettyJson(String json) { // https://stackoverflow.com/a/9583835/11996393 return new JSONObject(json).toString(4); } }
Source: GitHub
Breaking Down the Code
This code sets up the file path and API key, loads environment variables, and constructs a multipart form request. The HTML file is read and added to the request with the content type set to text/html
. The API key is included in the header, and the request is sent to the pdfRest Convert to PDF endpoint. The response is then printed to the console in a readable format.
Beyond the Tutorial
In this tutorial, we demonstrated how to use Java to make an API call to pdfRest's Convert to PDF tool for converting HTML files into PDFs programmatically. This is particularly useful for automating document conversion tasks within your applications.
To explore more features and tools offered by pdfRest, visit the API Lab. For detailed documentation, refer to the API Reference Guide.
Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at GitHub.