Search code examples
javahtmlcssitextitext7

iText 7 generate report with two page sizes using the same CSS Styling sheet with min-width & max-width features


I'm trying to convert HTML report to two different page sizes using iText 7 which is come in handy since I can set the page size using:

PageSize pageSize = PageSize.A3; 
pdf.setDefaultPageSize(pageSize);

But I'm trying to apply a trick on the CSS styling because I need to override some of the classes based on the page size such as for A3 >> table font size = 12pt while in LETTER >> the table font size = 6pt. The report holds really huge amount of data which I have to fit them inside both sizes. It's really challenging with LETTER size I used % for the font-size but since the content is dynamic sometimes the resulted report shown trimmed from the right side even ignoring the margin specification in the @Page selector that's why I need to specify it without % to avoid such problem. Furthermore, I'm trying to accomplish this task by overriding the styling with only one sheet. After searching, I came across one the @media coolest feature by using min-width and max-width feature as follow:

 @media only print and (min-width: 500px) and (max-width: 700px){
            body {
                background-color: yellow;
            }
            .box-table td, th {
                font-size: 6pt;
            }

        } 
@media only print and (min-width: 800px) and (max-width: 900px){
            body {
                background-color: green;
            }
            .box-table td, th {
                font-size: 12pt;
            }

        } 

Cool!! It works as an IF statement and one of them should fire at the time. I tested it with the screen element and it applied perfectly but with iText 7 only the last statement applied on both sizes. So, what am I missing? I'm trying to make it work with iText 7 PDF? Any ideas or suggestions?

Thanks.


Solution

  • The media device and media device description is not created or picked up by pdfHTML automatically, so you need to configure it manually with ConverterProperties:

    MediaDeviceDescription deviceDescription = new MediaDeviceDescription(MediaType.PRINT)
            .setWidth(PageSize.A3.getWidth());
    ConverterProperties properties = new ConverterProperties().setMediaDeviceDescription(deviceDescription);
    HtmlConverter.convertToPdf(..., ..., properties);