HTML2PDF - HTML to PDF Conversion - Java Sample Code

Sample code for using Apryse SDK to directly convert HTML pages to PDF by using 'pdftron.PDF.HTML2PDF', provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. The HTML2PDF converter supports conversion from a string or URL and offers many options to control page size and formatting.

To use this code, you'll need to

  1. Download and get started with Server SDK
  2. Install the HTML2PDF Module

Learn more about our Server SDK and PDF Conversion Library.

1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6import com.pdftron.pdf.*;
7import com.pdftron.sdf.*;
8
9public class HTML2PDFTest {
10 //---------------------------------------------------------------------------------------
11 // The following sample illustrates how to convert HTML pages to PDF format using
12 // the HTML2PDF class.
13 //
14 // 'pdftron.PDF.HTML2PDF' is an optional PDFNet Add-On utility class that can be
15 // used to convert HTML web pages into PDF documents by using an external module (html2pdf).
16 //
17 // html2pdf modules can be downloaded from https://docs.apryse.com/core/guides/info/modules#html2pdf-module.
18 //
19 // Users can convert HTML pages to PDF using the following operations:
20 // - Simple one line static method to convert a single web page to PDF.
21 // - Convert HTML pages from URL or string, plus optional table of contents, in user defined order.
22 // - Optionally configure settings for proxy, images, java script, and more for each HTML page.
23 // - Optionally configure the PDF output, including page size, margins, orientation, and more.
24 // - Optionally add table of contents, including setting the depth and appearance.
25 //---------------------------------------------------------------------------------------
26
27 public static void main(String[] args) {
28 String output_path = "../../TestFiles/Output/html2pdf_example";
29 String host = "https://docs.apryse.com";
30 String page0 = "/";
31 String page1 = "/all-products/";
32 String page2 = "/web/faq";
33 // The first step in every application using PDFNet is to initialize the
34 // library and set the path to common PDF resources. The library is usually
35 // initialized only once, but calling initialize() multiple times is also fine.
36 PDFNet.initialize(PDFTronLicense.Key());
37 // For HTML2PDF we need to locate the html2pdf module. If placed with the
38 // PDFNet library, or in the current working directory, it will be loaded
39 // automatically. Otherwise, it must be set manually using HTML2PDF.SetModulePath().
40 try {
41 HTML2PDF.setModulePath("../../../Lib");
42 if(!HTML2PDF.isModuleAvailable())
43 {
44 System.out.println();
45 System.out.println("Unable to run HTML2PDFTest: Apryse SDK HTML2PDF module not available.");
46 System.out.println("---------------------------------------------------------------");
47 System.out.println("The HTML2PDF module is an optional add-on, available for download");
48 System.out.println("at https://docs.apryse.com/core/guides/info/modules. If you have already downloaded this");
49 System.out.println("module, ensure that the SDK is able to find the required files");
50 System.out.println("using the HTML2PDF.setModulePath() function." );
51 System.out.println();
52 return;
53 }
54 } catch (Exception e) {
55 e.printStackTrace();
56 return;
57 }
58
59 //--------------------------------------------------------------------------------
60 // Example 1) Simple conversion of a web page to a PDF doc.
61
62 try (PDFDoc doc = new PDFDoc()) {
63 // now convert a web page, sending generated PDF pages to doc
64 HTML2PDF.convert(doc, host + page0);
65 doc.save(output_path + "_01.pdf", SDFDoc.SaveMode.LINEARIZED, null);
66 } catch (Exception e) {
67 e.printStackTrace();
68 return;
69 }
70
71 //--------------------------------------------------------------------------------
72 // Example 2) Modify the settings of the generated PDF pages and attach to an
73 // existing PDF document.
74
75 try (PDFDoc doc = new PDFDoc("../../TestFiles/numbered.pdf")) {
76 // open the existing PDF, and initialize the security handler
77 doc.initSecurityHandler();
78
79 // create the HTML2PDF converter object and modify the output of the PDF pages
80 HTML2PDF converter = new HTML2PDF();
81 converter.setPaperSize(PrinterMode.e_11x17);
82
83 // insert the web page to convert
84 converter.insertFromURL(host + page0);
85
86 // convert the web page, appending generated PDF pages to doc
87 converter.convert(doc);
88 doc.save(output_path + "_02.pdf", SDFDoc.SaveMode.LINEARIZED, null);
89 } catch (Exception e) {
90 e.printStackTrace();
91 return;
92 }
93
94 //--------------------------------------------------------------------------------
95 // Example 3) Convert multiple web pages
96
97 try (PDFDoc doc = new PDFDoc()) {
98 // convert page 0 into pdf
99
100 HTML2PDF converter = new HTML2PDF();
101
102 String header = "<div style='width:15%;margin-left:0.5cm;text-align:left;font-size:10px;color:#0000FF'><span class='date'></span></div><div style='width:70%;direction:rtl;white-space:nowrap;overflow:hidden;text-overflow:clip;text-align:center;font-size:10px;color:#0000FF'><span>PDFTRON HEADER EXAMPLE</span></div><div style='width:15%;margin-right:0.5cm;text-align:right;font-size:10px;color:#0000FF'><span class='pageNumber'></span> of <span class='totalPages'></span></div>";
103 String footer = "<div style='width:15%;margin-left:0.5cm;text-align:left;font-size:7px;color:#FF00FF'><span class='date'></span></div><div style='width:70%;direction:rtl;white-space:nowrap;overflow:hidden;text-overflow:clip;text-align:center;font-size:7px;color:#FF00FF'><span>PDFTRON FOOTER EXAMPLE</span></div><div style='width:15%;margin-right:0.5cm;text-align:right;font-size:7px;color:#FF00FF'><span class='pageNumber'></span> of <span class='totalPages'></span></div>";
104 converter.setHeader(header);
105 converter.setFooter(footer);
106 converter.setMargins("1cm", "2cm", ".5cm", "1.5cm");
107 HTML2PDF.WebPageSettings settings = new HTML2PDF.WebPageSettings();
108 settings.setZoom(0.5);
109 converter.insertFromURL(host + page0, settings);
110 converter.convert(doc);
111
112 // convert page 1 with the same settings, appending generated PDF pages to doc
113 converter.insertFromURL(host + page1, settings);
114 converter.convert(doc);
115
116 // convert page 2 with different settings, appending generated PDF pages to doc
117 HTML2PDF another_converter = new HTML2PDF();;
118 another_converter.setLandscape(true);
119 HTML2PDF.WebPageSettings another_settings = new HTML2PDF.WebPageSettings();
120 another_settings.setPrintBackground(false);
121 another_converter.insertFromURL(host + page2, another_settings);
122 another_converter.convert(doc);
123
124 doc.save(output_path + "_03.pdf", SDFDoc.SaveMode.LINEARIZED, null);
125 } catch (Exception e) {
126 e.printStackTrace();
127 return;
128 }
129
130 //--------------------------------------------------------------------------------
131 // Example 4) Convert HTML string to PDF.
132
133 try (PDFDoc doc = new PDFDoc()) {
134 HTML2PDF converter = new HTML2PDF();
135
136 // Our HTML data
137 String html = "<html><body><h1>Heading</h1><p>Paragraph.</p></body></html>";
138
139 // Add html data
140 converter.insertFromHtmlString(html);
141 // Note, InsertFromHtmlString can be mixed with the other Insert methods.
142
143 converter.convert(doc);
144 doc.save(output_path + "_04.pdf", SDFDoc.SaveMode.LINEARIZED, null);
145 } catch (Exception e) {
146 e.printStackTrace();
147 return;
148 }
149
150 //--------------------------------------------------------------------------------
151 // Example 5) Set the location of the log file to be used during conversion.
152
153 try (PDFDoc doc = new PDFDoc()) {
154 HTML2PDF converter = new HTML2PDF();
155 converter.setLogFilePath("../../TestFiles/Output/html2pdf.log");
156 converter.insertFromURL(host + page0);
157 converter.convert(doc);
158 doc.save(output_path + "_05.pdf", SDFDoc.SaveMode.LINEARIZED, null);
159 } catch (Exception e) {
160 e.printStackTrace();
161 return;
162 }
163
164 PDFNet.terminate();
165 }
166}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales