How to set size of PDF file using iText?

In previous article we have seen how to create pdf file using iText and add text into it. In this article we will discuss about the important aspect of the pdf files which is nothing but a size.
In previous article we created a document object which creates a document of a default size. But if we need to change the size of the PDF document we need to understand how the measurement is done in PDF.
Measurement unit used in iText is User Space Units. This User space unit is approximately same as the unit used in printing industry which is point (pt).
i.e. 1 in. = 25.4 mm = 72 user units

Now lets see how we can create a document of a specific size.

Rectangle pagesize = new Rectangle(360f, 720f);
Document document = new Document(pagesize, 36f, 72f, 108f, 180f);

The above code use the constructor

public Document(Rectangle pageSize,
float marginLeft,
float marginRight,
float marginTop,
float marginBottom)

Constructs a new Document object with Parameters:
pageSize - the pageSize
marginLeft - the margin on the left
marginRight - the margin on the right
marginTop - the margin on the top
marginBottom - the margin on the bottom

Here we are creating a rectangle of the 360 by 720 user space units, so document will be created of size 5 inch by 10 inch in size. It will also create the margins such as left margin of 0.5 in. (36/72), a right margin of 1 in. (72/72),a top margin of 1.5 in. (108/72), and a bottom margin of 2.5 in. (180/72).

Other way of setting the size is to use constructor Document(Rectangle pageSize)

In which you can directly pass the size of the rectangle to the Document constructor.

You can use the PageSize class from com.itextpdf.text.PageSize, to get number of rectangles representing the most common paper sizes.
Such as A0 to A10 format, letter, note, tabloid, legal, postcard , executive, B0 to B10, 11x17 and many more readymade rectangles you can use to create Document.

Creating Portrait PDF document using iText



To create Portrait PDF document using iText we need to use PageSize.A4 rectangle and pass to the Document object.


Document document = new Document(PageSize.A4);


Creating Landscape PDF document using iText



To create Portrait PDF document using iText we need to use PageSize.A4.rotate() rectangle and pass to the Document object.


Document document = new Document(PageSize.A4.rotate());
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

1 comments:

  1. I am having large number of columns, so exiting page sizes are not suitable for me, how can i ignore page size. if i add new column page should extend more horizontally. how can i achieve this. Please help me out.

    Thanks in Advance.

    ReplyDelete