View all our code samples

Using in Java is a package in the Java standard library that provides functionalities for networking operations. It includes classes and interfaces for working with URLs, establishing network connections, sending and receiving data over sockets, and handling network protocols.

We've implemented a code sample that you can re-use to convert your HTML documents to PDF, JPG, PNG or WEBP using PDFShift and Java:

import java.util.Base64;

public class Convert {
    public static byte[] convert(String apiKey, JsonObject params, String endpoint) throws Exception {
        if (!"pdf".equals(endpoint) && !"png".equals(endpoint) && !"jpg".equals(endpoint) && !"webp".equals(endpoint)) {
            throw new IllegalArgumentException("Invalid endpoint.");

        URL url = new URL("" + endpoint);
        String auth = "api:" + apiKey;
        String encoding = Base64.getEncoder().encodeToString(auth.getBytes()); 
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "Basic " + encoding);
        conn.setRequestProperty("Content-Type", "application/json");
        int responseCode = conn.getResponseCode();
        if(responseCode != 200) {
            throw new RuntimeException("HTTP POST failed with error code : " + responseCode);

        InputStream is = conn.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[1024];
        while ((nRead =, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        if(params.has("filename") || params.has("webhook")) {
            return new Gson().fromJson(new String(buffer.toByteArray()), JsonObject.class).toString().getBytes();

        return buffer.toByteArray();

Here's how you can use the above code:

public static void main(String[] args) throws Exception {
    String endpoint = "pdf";
    String apiKey = "sk_XXXXXXXXXXXXXX";
    JsonObject params = new JsonObject();
    params.addProperty("source", "");
    byte[] result = convert(apiKey, params, endpoint); 
    OutputStream outStream = new FileOutputStream("result.pdf");

We've tested this code with the latest version of and it's ready to be used in your project.

But if you were to encounter any bugs or issues while running it (or if you want to suggest changes to improve the code), please contact us and we'll be happy to help you out.