Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert HTML to PDF using Java
Convert HTML to PDF using Java
// initialize converter
Converter converter = new Converter("C:\\Files\\sample.html");
// define PDF convert options
PdfConvertOptions options = new PdfConvertOptions();
// convert
converter.convert("C:\\Files\\HtmlToPdf.pdf", options);
// initialize converter
Converter converter = new Converter("C:\\Files\\sample_2.html");
// define PDF convert options
PdfConvertOptions options = new PdfConvertOptions();
// define watermark options
WatermarkOptions watermark = new WatermarkOptions();
watermark.setText("THIS IS A SAMPLE TEXT WATERMARK");
watermark.setColor(Color.red);
watermark.setTop(400);
watermark.setLeft(150);
watermark.getWatermarkFont().setBold(true);
watermark.setRotationAngle(30);
watermark.setWidth(1000);
watermark.setHeight(1000);
watermark.setBackground(false);
options.setWatermark(watermark);
// convert
converter.convert("C:\\Files\\HtmlToPDFAddWatermark.pdf", options);
// input stream
InputStream stream = new URL("https://onlinebooks.library.upenn.edu/readers.html").openStream();
// initialize converter
Converter converter = new Converter(stream);
// define PDF convert options
PdfConvertOptions options = new PdfConvertOptions();
// convert
converter.convert("C:\\Files\\LoadDocumentFromUrl.pdf", options);
// initialize converter
Converter converter = new Converter("C:\\Files\\Conversion\\sample_2.html");
// define PdfConvertOptions
PdfConvertOptions options = new PdfConvertOptions();
options.setPageNumber(2);
options.setPagesCount(1);
// convert
converter.convert("C:\\Files\\ConvertNConsecutivePages.pdf", options);
// initialize converter
Converter converter = new Converter("C:\\Files\\sample.html");
// define PdfConvertOptions
PdfConvertOptions options = new PdfConvertOptions();
options.setPassword("12345");
options.setRotate(Rotation.On180);
options.setDpi(300);
options.setWidth(1024);
options.setHeight(768);
// convert
converter.convert("C:\\Files\\ConvertWithAdvancedOptions.pdf", options);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment