How to Convert a URL to a PDF using Java

Cloudmersive
2 min readSep 6, 2022

--

PDF is an excellent destination format for dozens of common file types — including URLs. Rendering a URL in PDF format is a great way to maintain a static iteration of that website’s front page & store it easily within your file system. With our URL to PDF API, you can accomplish that operation easily & for free (all you need to do is register a free account on our website & use your secure API key to authenticate the service). Below, I’ll demonstrate how you can easily structure your API call using ready-to-run code examples in Java. All you need to do is copy & paste, and you’re good to go.

We can install the API client with Maven by first adding a reference to the repository in pom.xml:

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

And after that we can add a reference to the dependency in pom.xml:

<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v4.25</version>
</dependency>
</dependencies>

Now we can move switch gears to our controller & add the following imports to the top of our file:

// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.ConvertWebApi;

We can now complete the API call with the final snippet below:

ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");
ConvertWebApi apiInstance = new ConvertWebApi();
UrlToPdfRequest input = new UrlToPdfRequest(); // UrlToPdfRequest | URL to PDF request parameters
try {
byte[] result = apiInstance.convertWebUrlToPdf(input);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertWebApi#convertWebUrlToPdf");
e.printStackTrace();
}

Within the above snippet, we need to now satisfy the URL to PDF request parameters. These include options to specify any extra loading time we want to give for the website to render in the PDF, whether or not we want background graphics included in the rendering, and more. Our request should follow the below format:

{
"Url": "string",
"ExtraLoadingWait": 0,
"IncludeBackgroundGraphics": true,
"ScaleFactor": 0
}

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet