Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set orientation to Landscape in iText 7

Tags:

java

itext

itext7

I am converting html to pdf using iText7 with method convertToPdf(). PDF is getting generated properly but Landscape mode is not working.

Can some one tell how to get Landscape mode?

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.styledxmlparser.css.media.MediaDeviceDescription;
import com.itextpdf.styledxmlparser.css.media.MediaType;

import java.io.File;
import java.io.IOException;

import static com.itextpdf.html2pdf.css.CssConstants.LANDSCAPE;

public class htmlToPDF {

    public static void main(String args[]) throws IOException {

        ConverterProperties properties = new ConverterProperties();

        MediaDeviceDescription med = new MediaDeviceDescription(MediaType.ALL);
        med.setOrientation(LANDSCAPE);
        properties.setMediaDeviceDescription(med);

        HtmlConverter.convertToPdf(new File("D:\\test.html"), new File("D:\\test.pdf"),properties);
    }
}
like image 480
NeedToLearn Avatar asked Jan 24 '19 13:01

NeedToLearn


1 Answers

Please just use a converter method that takes PdfDocument as a parameter. For example, the next one : convertToPdf(InputStream htmlStream, PdfDocument pdfDocument, ConverterProperties converterProperties)

Now the only thing you need is to set the page size to the document before converting the html file.

    PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new File(sourcePath)));
    pdfDocument.setDefaultPageSize(PageSize.A4.rotate());
    HtmlConverter.convertToPdf(new FileInputStream(destPath), pdfDocument, props);
like image 68
Uladzimir Asipchuk Avatar answered Oct 02 '22 09:10

Uladzimir Asipchuk