How to convert HTML to PDF using Java

The Pdfcrowd API is an online tool that lets you easily export web pages and raw HTML code to PDF in your Java applications. PDFs are generated in the cloud, no 3rd party libraries are needed. All you need is a tiny Java API client library.

Here are some samples created with the API. Click a thumbnail to open the PDF.


JavaScript vector chart

Wikipedia page

Status report

Invoice

Newsletter

     

Code samples

This code converts a web page to PDF and saves it to a file:

import com.pdfcrowd.*;
import java.io.*;
 
// create an API client instance
Client client = new Client("username", "apikey");

// convert a web page and save the PDF to a file
FileOutputStream fileStream = new FileOutputStream("google_com.pdf");
client.convertURI("http://google.com/", fileStream);
fileStream.close();

You can also convert raw HTML code, just use the convertHtml() method instead of convertURI():

FileOutputStream fileStream = new FileOutputStream("MyHtml.pdf");
client.convertHtml("<body>My HTML Layout</body>", fileStream);
fileStream.close();

Or use convertFile() to convert a local HTML file:

fileStream = new FileOutputStream("MyLayout.pdf");
client.convertFile("/path/to/MyLayout.html", fileStream);
fileStream.close();

Did you know ...

  • PDF is a cross platform standard. Somebody can create a PDF file on a Linux workstation and you can open it on a PC or Mac and still see the document just like it was intended to be viewed.
  • PDF was developed by Adobe Systems in 1993
  • PDF encapsulates a complete description of fixed-layout flat document.

Other Languages