iText landscape orientation and positioning?

55,929

Solution 1

You're using PageSize.A4_LANDSCAPE, a variable that was introduced by a contributor and that should have never been added to the main release. Please use PageSize.A4.rotate() instead.

It's not clear what you want to achieve with the lines:

document.left(100f);
document.top(150f);

Those are getters, not setters. It looks as if you're assuming that PDF is similar to HTML. That assumption is wrong.

If you want the image to be put 10 user units from the left and 15 user units from the top (in which case 100 and 150 are the wrong values), you could replace the 0 values in your Document constructor to define a left margin of 10 user units and the top margin 15 user units.

Another way would be to define an absolute position for the image with the method setAbsolutePosition(). In that case, you need to be aware that the coordinate system is oriented in such a way that the lower-left corner of the page has the coordinate x=0 , y=0 for documents created from scratch.

Solution 2

You can use this example this is work for me

 Document document = new Document();
 document.setPageSize(PageSize.A4.rotate());

Solution 3

iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10f, 10f, 10f, 0f);
Share:
55,929
user1111929
Author by

user1111929

Updated on March 29, 2020

Comments

  • user1111929
    user1111929 over 4 years

    I've just started to work with iText (5.4.2, latest version) and there are two things that I haven't yet managed to get straight.

    • Creating documents in landscape. All pages are rendered portrait.
    • Inserting images on a given position (number of millimeters from top & left).

    I have the code below.

    Document d = new Document(PageSize.A4_LANDSCAPE,0,0,0,0);
    PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream("C:/test.pdf"));
    document.open();
    document.newPage();
    Image img = Image.getInstance(String.format("C:/file.png"));
    img.scaleToFit(400,240);
    document.left(100f);
    document.top(150f);
    document.add(img);
    document.close();
    

    But the page is rendered in Portrait (not Landscape) and the image is put in the top left corner (not 10 and 15 units away from it as requested). What am I doing wrong?