Home » Java » How to convert HTML String to PDF using ConvertAPI (without a physical file)

How to convert HTML String to PDF using ConvertAPI (without a physical file)

Posted by: admin June 30, 2018 Leave a comment


Previously I was using http://do.convertapi.com/Web2Pdf to convert HTML String to PDF using a simple GET request (not POST) using Java. The entire content was passed using curl parameter.

However, that API seems to have stopped working recently. I’m trying to port over to https://v2.convertapi.com/web/to/pdf but I cannot find a sample to do the same using the new API either with GET or POST.

Can someone provide an example to make a GET or POST request using Java?

UPDATE: Here’s the code that I have so far. I can get the request to be successful, and get a response code 200. I’m still trying to figure out how to parse the response to get the PDF file.

private static final String WEB2PDF_API_URL = "https://v2.convertapi.com/html/to/pdf";
private static final String WEB2PDF_SECRET = "secret-here";

String htmlContent = "valid HTML content here";
String encodedContent = URLEncoder.encode(htmlContent, "UTF-8");

URL apiUrl = new URL(WEB2PDF_API_URL + "?secret=" + WEB2PDF_SECRET + "&download=inline&PageOrientation=landscape&MarginLeft=0&MarginRight=0&MarginTop=0&MarginBottom=0");
HttpURLConnection connection = null;

ByteArrayOutputStream buffer = null;

connection = (HttpURLConnection) apiUrl.openConnection();
connection.setRequestProperty("Content-Disposition", "attachment; filename=\"data.html\"");
connection.setRequestProperty("Content-Type", "application/octet-stream");

/* write request */
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

/* read response */
String responseMessage = connection.getResponseMessage();
logger.info("responseMessage: " + responseMessage);

int statusCode = connection.getResponseCode();
logger.info("statusCode: " + statusCode);

if (statusCode == HttpURLConnection.HTTP_OK) {
    logger.info("HTTP status code OK");
    // parse output