How to find out the current cursor position on a page?
I add a bunch of stuff to a page, using a sequence of document.add()
statements. Then I add a table that fills two columns at absolute positoins using the ColumnText
object:
column.setSimpleColumn( x[count][0], document.bottom(), x[count][1], document.top() - height - 10);
height
is set to 0. This places the table in a column that starts at the top of the document. Of course, what I'd like to do is to add the column directly below the last thing written to the document in the final document.add()
statement. If I knew the height consumed thus far on the page, I could manually enter the correct height
value and things work fine.
The problem is, what gets written in the document depends on a lot of conditions, so I'd like to execute a command to tell me how much height has been consumed thus far in the document (for the current page) so I can set height
appropriately. Is there a way to do this in iText so that I don't need to keep track of the heights of each individual element added to the page?
Posted on StackOverflow on Oct 30, 2015 by user46688
There are three ways to add content to a PDF:
Using document.add();
In this case, iText decides where the content is added, based on the page size and the margins you defined.
There is a very old method called getVerticalPosition()
that takes a boolean
as parameter. I'm not proud of that method as it is a getter method that not only will give you the Y position on the page after using a series of document.add()
operations, it can also change the current Y position (and that is not what a getter method should do).
If you pass false
as a parameter, it will give you the current Y, which could be the position of the baseline of the last Chunk
you've added.
If you pass true
as a parameter, the method will first add a newline and give you the position of the baseline of the "next" line of text you'll be adding.
Using ColumnText
ColumnText is an object to which you can add Elements
. You can then define a column using absolute coordinates and invoke the go()
method. The go()
method will render the content and you can use the return value to see if the content fitted the rectangle. You can use the getYLine()
method to find the Y coordinate of the last piece of content that was added.
Using writeSelectedRows()
This method will only work when you work with PdfPTable
objects. The writeSelectedRows()
method can add a selection of rows and columns to a page starting at a specific x
and y
coordinate. It returns a float
value that gives you the Y-position of the bottom border of the final row that was added. If you want to know how much space the table needs vertically before adding the table with writeSelectedRows()
, you need to calculate the height of the rows you want to add first.