How to get vertical cursor position when writing document in iText 7?

女生的网名这么多〃 提交于 2019-11-29 17:17:26

The link Jon Reilly posted in the comment, which goes here, is very useful to figuring this out:

You will need a reference to the the element whose vertical position you need and add it:

Paragraph p = new Paragraph("Hello World");
doc.add(p);

You can then get the IRenderer of the element as follows, this then allows you to get the LayoutResult, which has lots of useful information about the rendering of the element in the PDFDocument, including the bounding box, with the full coordinates, width, height, etc. which should be strictly more powerful than the old iText5 getVerticalPosition.

IRenderer pRenderer = p.createRendererSubTree().setParent(doc.getRenderer());
LayoutResult pLayoutResult = pRenderer.layout(new LayoutContext(new LayoutArea(0, new Rectangle(595-72, 842-72))));

float y = pLayoutResult.getOccupiedArea().getBBox().getY();
float x = pLayoutResult.getOccupiedArea().getBBox().getX();

I think asking document renderer about the top of its current layout area is a simpler way to obtain this information.

Paragraph p = new Paragraph("Hello World");
doc.add(p);
float position = doc.getRenderer().getCurrentArea().getBBox().getTop();

I know too little about the API to be aware of the downsides of this method. It looks like it's working, and for me it's enough.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!