Java HTML to PDF Code Examples
Complete Java examples for common HTML to PDF tasks. See the Java SDK guide for installation and result handling.
You can run the examples below with the displayed API credentials. Update the input URLs and filenames as needed. Each Java example can be copied and run independently.
Basic examples
Choose file, in-memory, or output-stream handling for the result. Stream examples use a file stream as their destination.
Convert a URL
Save to a file
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.convertUrlToFile("https://example.com/", "example.pdf"); } }
Keep in memory
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); byte[] pdf = client.convertUrl("https://example.com/"); System.out.println(pdf.length); } }
Write to a stream
import com.pdfcrowd.Pdfcrowd; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); try (OutputStream output_stream = Files.newOutputStream(Path.of("example.pdf"))) { client.setContentViewportWidth("balanced"); client.convertUrlToStream("https://example.com/", output_stream); } } }
Convert an HTML file
Upload an existing document.html file. For local images and stylesheets, see Local assets.
Save to a file
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.convertFileToFile("document.html", "document.pdf"); } }
Keep in memory
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); byte[] pdf = client.convertFile("document.html"); System.out.println(pdf.length); } }
Write to a stream
import com.pdfcrowd.Pdfcrowd; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); try (OutputStream output_stream = Files.newOutputStream(Path.of("document.pdf"))) { client.setContentViewportWidth("balanced"); client.convertFileToStream("document.html", output_stream); } } }
Send HTML content
These examples read HTML text from document.html. In an application, pass the HTML produced by your template renderer instead.
Save to a file
import com.pdfcrowd.Pdfcrowd; import java.nio.file.Files; import java.nio.file.Path; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); String html = Files.readString(Path.of("document.html")); client.setContentViewportWidth("balanced"); client.convertStringToFile(html, "html.pdf"); } }
Keep in memory
import com.pdfcrowd.Pdfcrowd; import java.nio.file.Files; import java.nio.file.Path; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); String html = Files.readString(Path.of("document.html")); client.setContentViewportWidth("balanced"); byte[] pdf = client.convertString(html); System.out.println(pdf.length); } }
Write to a stream
import com.pdfcrowd.Pdfcrowd; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); try (OutputStream output_stream = Files.newOutputStream(Path.of("html.pdf"))) { String html = Files.readString(Path.of("document.html")); client.setContentViewportWidth("balanced"); client.convertStringToStream(html, output_stream); } } }
Convert inline HTML
Define a small HTML document directly in your code.
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); String html = "<!doctype html>\n" + "<html><body><h1>Monthly report</h1></body></html>"; client.setContentViewportWidth("balanced"); client.convertStringToFile(html, "report.pdf"); } }
Read from an input stream
Open document.html as a binary input stream and save the PDF to document.pdf.
import com.pdfcrowd.Pdfcrowd; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); try (InputStream input_stream = Files.newInputStream(Path.of("document.html"))) { client.setContentViewportWidth("balanced"); client.convertStreamToFile(input_stream, "document.pdf"); } } }
Local assets
Include HTML and its local images, stylesheets, and scripts in a ZIP archive, keeping their relative paths.
Convert a prepared archive
Upload an existing document.zip. Select the main HTML file explicitly when the archive contains multiple documents.
Detect the main HTML file
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.convertFileToFile("document.zip", "output.pdf"); } }
Select index.html
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setZipMainFilename("index.html"); client.convertFileToFile("document.zip", "document.pdf"); } }
Convert a local directory
Create document.zip from the existing document directory, then convert it to PDF.
import com.pdfcrowd.Pdfcrowd; import java.nio.file.Files; import java.nio.file.Path; import java.util.Iterator; import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); Path directory = Path.of("document"); try (ZipOutputStream archive = new ZipOutputStream( Files.newOutputStream(Path.of("document.zip"))); Stream<Path> files = Files.walk(directory)) { Iterator<Path> paths = files.filter(Files::isRegularFile).sorted().iterator(); while (paths.hasNext()) { Path path = paths.next(); String name = directory.relativize(path).toString() .replace('\\', '/'); archive.putNextEntry(new ZipEntry(name)); Files.copy(path, archive); archive.closeEntry(); } } client.setContentViewportWidth("balanced"); client.setZipMainFilename("index.html"); client.convertFileToFile("document.zip", "document.pdf"); } }
Create an archive in memory
Package the existing document directory in memory. Its index.html file can refer to other files in the directory by relative path.
import com.pdfcrowd.Pdfcrowd; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Iterator; import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); Path directory = Path.of("document"); ByteArrayOutputStream archive = new ByteArrayOutputStream(); try (ZipOutputStream zip = new ZipOutputStream(archive); Stream<Path> files = Files.walk(directory)) { Iterator<Path> paths = files.filter(Files::isRegularFile).sorted().iterator(); while (paths.hasNext()) { Path path = paths.next(); String name = directory.relativize(path).toString() .replace('\\', '/'); zip.putNextEntry(new ZipEntry(name)); Files.copy(path, zip); zip.closeEntry(); } } client.setContentViewportWidth("balanced"); client.setZipMainFilename("index.html"); try (InputStream input_stream = new ByteArrayInputStream(archive.toByteArray())) { client.convertStreamToFile(input_stream, "document.pdf"); } } }
Page rendering
Set page size and margins
Use landscape Letter pages with half-inch margins.
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setMarginBottom("0.5in"); client.setMarginLeft("0.5in"); client.setMarginRight("0.5in"); client.setMarginTop("0.5in"); client.setOrientation("landscape"); client.setPageSize("Letter"); client.convertUrlToFile("https://example.com/", "page-layout.pdf"); } }
Add a header and page numbers
Show the source URL in the header and “Page N of M” in the footer.
See the headers and footers guide for more layouts and placeholders.
Scale page content
Scale the HTML content to 300%.
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setScaleFactor(300); client.convertUrlToFile("https://example.com/", "zoom_300.pdf"); } }
Choose a responsive layout
The browser viewport controls responsive breakpoints independently of the PDF paper size.
Large viewport
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("large"); client.setNoMargins(true); client.convertUrlToFile("https://example.com/", "bootstrap.pdf"); } }
Small viewport
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("small"); client.convertUrlToFile("https://example.com/", "viewport_small.pdf"); } }
Hide or restyle page elements
Replace the selectors with elements from your page.
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setCustomCss("/* Hide navigation, ads, and sidebar */\n" + "nav, .advertisement, .sidebar, footer {\n" + " display: none !important;\n" + "}\n" + "/* Adjust layout for print */\n" + ".content {\n" + " width: 100% !important;\n" + " max-width: none !important;\n" + "}"); client.convertUrlToFile("https://example.com/", "custom_css.pdf"); } }
Modify the page with JavaScript
Adjust the selectors and class names for your page.
Remove widgets and expand sections
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setCustomJavascript("// Remove dynamic content before conversion\n" + "document.querySelectorAll('.video-player, .chat-widget').forEach(el => {\n" + " el.remove();\n" + "});\n" + "// Expand collapsed sections\n" + "document.querySelectorAll('.collapsed').forEach(el => {\n" + " el.classList.remove('collapsed');\n" + "});"); client.convertUrlToFile("https://example.com/", "custom_js.pdf"); } }
Add content to the page
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setCustomJavascript("el = document.createElement('h2');\n" + "el.textContent = 'Hello from PDFCrowd API';\n" + "el.style.color = 'red';\n" + "el_before = document.getElementsByTagName('h1')[0];\n" + "el_before.parentNode.insertBefore(el, el_before.nextSibling);"); client.convertUrlToFile("https://example.com/", "html_inject.pdf"); } }
Convert a specific element
Convert only #main in an existing document.html file. Adjust the filename and selector for your document.
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setElementToConvert("#main"); client.convertFileToFile("document.html", "html_part.pdf"); } }
Wait for a page element
Wait for #content-loaded to appear in an existing document.html file. Choose an element that appears when your content is ready.
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setWaitForElement("#content-loaded"); client.convertFileToFile("document.html", "wait_element.pdf"); } }
Allow extra time for JavaScript
Add a delay of 2000 milliseconds. When the page has a reliable readiness marker, use Wait for a page element.
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setJavascriptDelay(2000); client.convertUrlToFile("https://example.com/", "with_delay.pdf"); } }
Apply print stylesheets
Apply the page’s @media print rules. The page must provide print styles for this to change its appearance.
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setUsePrintMedia(true); client.convertUrlToFile("https://example.com/", "print_media.pdf"); } }
Inspect element boundaries
Highlight element boxes to investigate spacing and layout.
Highlight backgrounds
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setCustomJavascript("libPdfcrowd.highlightHtmlElements({\n" + " backgroundColor: 'rgba(255, 191, 0, 0.1)',\n" + " borderColor: null\n" + "});"); client.convertUrlToFile( "https://example.com/", "highlight_background.pdf" ); } }
Add borders and spacing
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setCustomJavascript("libPdfcrowd.highlightHtmlElements({\n" + " borderColor: 'orange',\n" + " backgroundColor: null,\n" + " padding: '4px',\n" + " margin: '4px'\n" + "});"); client.convertUrlToFile( "https://example.com/", "highlight_borders.pdf" ); } }
HTML and CSS
Add these fragments to HTML you control.
Remove or hide elements
<nav class="pdfcrowd-remove">This won't appear in the PDF</nav> <div class="pdfcrowd-hide">This is invisible but takes up space</div>
pdfcrowd-remove removes the element from the layout. pdfcrowd-hide preserves its space.
Control page breaks
<!-- Force a page break before the following section --> <div style="page-break-before: always"></div> <!-- Avoid breaking tables across pages --> <style> table, tr, td { page-break-inside: avoid; } </style>
Content taller than a page still needs to break.
Apply styles only during conversion
<style> /* These styles only apply during PDF conversion */ .pdfcrowd-body h1 { font-size: 48px; } .pdfcrowd-body footer { display: none; } .pdfcrowd-body .main-content { width: 100%; } </style>
The .pdfcrowd-body prefix limits these rules to conversion; it does not change the page in a visitor’s browser.
Templates
Render a template with JSON data
Upload existing template.html and data.json files. See the template rendering guide for template syntax, data mapping, and other supported data formats.
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setDataFormat("json"); client.setDataFile("data.json"); client.convertFileToFile("template.html", "output.pdf"); } }
PDF features
Create a fillable PDF
Use an existing form.html file containing HTML form controls.
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setContentViewportWidth("balanced"); client.setEnablePdfForms(true); client.convertFileToFile("form.html", "form.pdf"); } }
See fillable PDF forms for supported controls and attributes.
Set PDF metadata
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setAuthor("PDFCrowd"); client.setKeywords("PDFCrowd,demo"); client.setSubject("Demo"); client.setTitle("Hello World"); client.convertUrlToFile("https://example.com/", "with_metadata.pdf"); } }
Set a presentation view
import com.pdfcrowd.Pdfcrowd; class Example { public static void main(String[] args) throws Exception { Pdfcrowd.HtmlToPdfClient client = new Pdfcrowd.HtmlToPdfClient("demo", "demo"); client.setInitialZoomType("fit-page"); client.setNoMargins(true); client.setOrientation("landscape"); client.setPageLayout("single-page"); client.setPageMode("full-screen"); client.convertUrlToFile("https://example.com/", "slide_show.pdf"); } }
These settings request a full-screen initial view with landscape pages. The PDF viewer controls whether it honors those preferences.