Search code examples
javaitexthtml-to-pdf

Convert html to pdf in landscape mode using iText


I'm trying to convert html to pdf using iText. Here is the simple code that is working fine :

ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
HtmlConverter.convertToPdf(htmlAsStringToConvert, pdfStream)

Now, I want to convert the pdf to LANDSCAPE mode, so I've tried :

ConverterProperties converterProperties = new ConverterProperties();
  MediaDeviceDescription mediaDeviceDescription = new MediaDeviceDescription(MediaType.SCREEN);
  mediaDeviceDescription.setOrientation(LANDSCAPE);
  converterProperties.setMediaDeviceDescription(mediaDeviceDescription);
  HtmlConverter.convertToPdf(htmlAsStringToConvert, pdfStream, converterProperties);

and also :

 PdfDocument pdfDoc = new PdfDocument(writer);
  pdfDoc.setDefaultPageSize(PageSize.A4.rotate());
  HtmlConverter.convertToPdf(htmlAsStringToConvert, pdfDoc, new ConverterProperties()).

I've also mixed both, but the result remains the same, the final PDF is still in default mode.


Solution

  • The best way to achieve landscape page size when converting HTML to PDF is to provide the corresponding CSS instruction for the page to become landscape.

    This is done with the following CSS:

    @page {
        size: landscape;
    }
    

    Now, if you have your input HTML document in htmlAsStringToConvert variable then you can process it as an HTML using Jsoup library which iText embeds. Basically we are just adding the necessary CSS instruction into our <head>:

    Document htmlDoc = Jsoup.parse(htmlAsStringToConvert);
    htmlDoc.head().append("<style>" +
            "@page { size: landscape; } "
            + "</style>");
    
    HtmlConverter.convertToPdf(htmlDoc.outerHtml(), new FileOutputStream(outPdf));
    

    Beware that if you already have @page declarations in your HTML then the one you append might be in conflict with the ones you already have - in this case, you need to make sure you insert your declaration as the latest one (this should be the case with the code above as long as all of your declaration are in <head> element).