【问题标题】:How to fit a String inside a rectangle?如何将字符串放入矩形内?
【发布时间】:2012-11-23 09:23:13
【问题描述】:

我正在尝试将一些字符串、图像和表格添加到我的 pdf 文件中(必须有几页)但是当我尝试使用 ColumnText 时(我使用它是因为我想将字符串放置在绝对位置) ,我遇到一个问题。 当列高不足以添加字符串的内容时,内容不完整。如何避免内容丢失?

以下是相关代码:

try {
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    String imageUrl = "/Users/nofear/workspace/deneme23/pics/a4-ust.png";
    String imageUrlAlt = "pics/a4-alt.png";
    Image imageust = null;
    Image imageAlt = null;
    try {
        imageust = Image.getInstance(imageUrl);
        imageAlt = Image.getInstance(imageUrlAlt);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("HEIGHT"
        + (document.getPageSize().getHeight() - imageust.getHeight()));
    imageust.setAbsolutePosition(0f,
        document.getPageSize().getHeight() - imageust.getHeight()-10);
    imageAlt.setAbsolutePosition( 0f, 10f);
    document.add(imageust);
    document.add(imageAlt);
    // now draw a line below the headline
    cb.setLineWidth(1f); 
    cb.moveTo(0, 200);
    cb.lineTo(200, 200);
    cb.stroke();
    // first define a standard font for our text
    Font helvetica8BoldBlue = FontFactory.getFont(FontFactory.HELVETICA,16);
    // create a column object
    ColumnText ct = new ColumnText(cb);
    // define the text to print in the column
    Phrase myText = new Phrase("Very Very Long String!!!" , helvetica8BoldBlue);
    ct.setSimpleColumn(myText, 60, 750,
        /* width*/document.getPageSize().getWidth() - 40, 100,
        20, Element.ALIGN_LEFT);
    ct.go();
} catch (Exception e) {
} finally {
    document.close();
}

【问题讨论】:

    标签: itext


    【解决方案1】:

    共有三个选项:

    1. 您可以提供一个更大的矩形,以便内容适合里面,
    2. 或者你减少内容(例如更小的字体,更少的文字),...
    3. 保持矩形大小,保持字体大小等...但添加不适合下一页的内容。

    你怎么知道内容不合适?

    您可以先在模拟模式下添加内容,然后测试是否所有内容都被“消费”了:

    int status = ct.go(true);
    boolean fits = !ColumnText.hasMoreText(status);
    

    根据fits 的值,您可以决定更改矩形的大小或内容。有一个例子说明了如何做到这一点:http://itextpdf.com/examples/iia.php?id=163

    如果你可以将内容分布到不同的页面,你不需要模拟模式,你只需要插入一个document.newPage();

    ColumnText ct = new ColumnText(cb);
    ct.setSimpleColumn(rect);
    int status = ct.go();
    while (ColumnText.hasMoreText(status)) {
        document.newPage();
        ct.setSimpleColumn(rect);
        status = ct.go();
    }
    

    在此示例中,rect 包含矩形的坐标。

    【讨论】:

    • 您提供的 2 个选项并不能解决我的问题,因为字体大小必须保持不变,因此如果内容达到矩形大小,则必须使用简单的列将内容换行到另一个页面。跨度>
    • 好的,我添加了第三个选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    相关资源
    最近更新 更多