How to set PDF page size A4 when we use ITextRenderer to generate PDF from thymeleaf HTML template ?
I have generated PDF but page size is not proper, how to set page size A4 ITextRenderer library in JAVA
ClassLoaderTemplateResolver templateResolver = new
ClassLoaderTemplateResolver();
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
Context context = new Context();
context.setVariable("name", "Thomas");
String html = templateEngine.process("templates/Quote", context);
OutputStream outputStream = new FileOutputStream("message.pdf");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(outputStream,true);
outputStream.close();
Please be aware that you are using FlyingSaucer
, not iText
.
FlyingSaucer
is a product that internally uses (a very old version of) iText
.
You are immediately cutting yourself off from 10+ years of bugfixes and developments.
If you are comfortable going for just iText
, the best way of solving this issue is with pdfHTML.
It's an add-on we wrote to the iText7 core library that is specifically designed to convert HTML into PDF.
Simple example:
File src = new File("source_html_file.html");
File dest = new File("target_pdf_file.pdf");
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdf, PageSize.A4);
InputStream stream = new FileInputStream(src);
ConverterProperties converterProperties = new ConverterProperties();
FontProvider dfp = new DefaultFontProvider(true, true, true);
converterProperties.setFontProvider(dfp);
HtmlConverter.convertToPdf(stream, pdf, converterProperties);
Check out the tutorials online for more information
https://developers.itextpdf.com/content/itext-7-examples/itext-7-converting-html-pdf