I convert HTML to PDF using iText7 with the convertToPDF()
method of pdfHTML. I would like to change the page orientation for a few specific pages in my PDF document. The content of these pages is dynamic, and we cannot guess how many pages that should be in landscape (i.e. content of dynamic table could take more than one page)
Current situation: I create a custom worker (implements ITagWorker) which landscape the page that following the tag <landscape/>
public byte[] generatePDF(String html) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfWriter pdfWriter = new PdfWriter(byteArrayOutputStream);
PdfDocument pdfDocument = new PdfDocument(pdfWriter);
try {
ConverterProperties properties = new ConverterProperties();
properties.setTagWorkerFactory(
new DefaultTagWorkerFactory() {
@Override
public ITagWorker getCustomTagWorker(
IElementNode tag, ProcessorContext context) {
if ("landscape".equalsIgnoreCase(tag.name())) {
return new LandscapeDivTagWorker();
}
return null;
}
} );
MediaDeviceDescription mediaDeviceDescription = new MediaDeviceDescription(MediaType.PRINT);
properties.setMediaDeviceDescription(mediaDeviceDescription);
HtmlConverter.convertToPdf(html, pdfDocument, properties);
} catch (IOException e) {
e.printStackTrace();
}
pdfDocument.close();
return byteArrayOutputStream.toByteArray();
}
The custom worker :
public class LandscapeDivTagWorker implements ITagWorker {
@Override
public void processEnd(IElementNode element, ProcessorContext context) {
}
@Override
public boolean processContent(String content, ProcessorContext context) {
return false;
}
@Override
public boolean processTagChild(ITagWorker childTagWorker, ProcessorContext context) {
return false;
}
@Override
public IPropertyContainer getElementResult() {
return new AreaBreak(new PageSize(PageSize.A4).rotate());
}
}
Is there a way to define all the content that should be displayed in landscape?
Something like:
<p>Display in portrait</p>
<landscape>
<div>
<p>display in landscape</p>
…
<table>
..
</table>
</div>
</landscape>
or with a CSS class :
<p>Display in portrait</p>
<div class="landscape">
<p>display in landscape</p>
…
<table>
..
</table>
</div>
Result => 1 page in portrait and other pages in landscape (All the div content should be in landscape)
PS: I follow this hint Change page orientation for only some pages in the resulting PDF (created out of html) by using a custom CssApplierFactory but the result was the same => just the first page where the landscape class is used was in landscape and the other content of the table was in portrait