iText7:如何获取段落的实际宽度 [英] iText7: How to get the real width of a Paragraph

查看:115
本文介绍了iText7:如何获取段落的实际宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在添加到文档之前,我需要知道一个段落的宽度(以磅为单位).我在这里搜索,发现阿列克谢有关段落高度的答案.因此,我用宽度制作了它,但是它不起作用.无论段落多长时间,始终返回矩形的宽度. 我尝试了这段代码:

I need to know the width (in point) of a Paragraph before add to the document. I searched here and found Alexey answer about Paragraph's height. So I made it with width, but it doesn't work. Always return the Rectangle's width no matter how long the Paragraph. I tried this code:

private float getRealParagraphWidth(Document doc, Paragraph paragraph) {
  // Create renderer tree
  IRenderer paragraphRenderer = paragraph.createRendererSubTree();
  // Do not forget setParent(). Set the dimensions of the viewport as needed
  LayoutResult result = paragraphRenderer.setParent(doc.getRenderer()).
        layout(new LayoutContext(new LayoutArea(1, new Rectangle(1000, 100))));
  // LayoutResult#getOccupiedArea() contains the information you need
  return result.getOccupiedArea().getBBox().getWidth();
}

所以,我的问题是,如果此代码适用于高度而不适用于宽度,那么这又有什么问题呢?

So, my question is, what is wrong with this code if it works with height, but not with width?

推荐答案

我的一个朋友解决了它.代码的最后一行应该是这一行:

A friend of mine solved it. The last line of the code should be this one:

 private float getRealParagraphWidth(Document doc, Paragraph paragraph) {
    // Create renderer tree
    IRenderer paragraphRenderer = paragraph.createRendererSubTree();
    // Do not forget setParent(). Set the dimensions of the viewport as needed
    LayoutResult result = paragraphRenderer.setParent(doc.getRenderer()).
            layout(new LayoutContext(new LayoutArea(1, new Rectangle(1000, 100))));
    // LayoutResult#getOccupiedArea() contains the information you need
    //return result.getOccupiedArea().getBBox().getWidth();
    return ((ParagraphRenderer) paragraphRenderer).getMinMaxWidth().getMaxWidth();
 }

它得出正确的值.

这篇关于iText7:如何获取段落的实际宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆