Add the below dependency in your project.
implementation 'com.itextpdf:html2pdf:3.0.2'
Java Code :
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class HtmlToPdfConvertor
{
public static void main(String[] args) throws IOException
{
String html_Name = index.html;
String outpuFileName = output.pdf;
final String html_String = Files.readAllBytes(Path.of(html_Name));
try (FileOutputStream fos = new FileOutputStream(outputFileName))
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument doc = new PdfDocument(new PdfWriter(baos)); doc.setDefaultPageSize(PageSize.A4);
ConverterProperties props = new ConverterProperties();
HtmlConverter.convertToPdf(html, doc, props); fos.write(baos.toByteArray());
}
}
}