首页 > 解决方案 > 单元格的文本不呈现并警告“元素不适合当前区域”

问题描述

我正在使用 iText 7.2.0(Java 8,Windows Server 2016)制作表格。

表格不需要溢出(比页面宽),但如果需要,可以在单词中间打破单元格事件。

某些单元格的文本未呈现,我收到此警告:

[main] 警告 com.itextpdf.layout.renderer.RootRenderer - 元素不适合当前区域。

如果我稍微更改一下文本(例如将“i”替换为“I”),它就会起作用。

我该如何解决?这是我的代码或 iText 中的错误吗?

import java.io.FileNotFoundException;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.Style;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.properties.UnitValue;

public class Main {
    private static void makeCell(Table table, Style style, String text) {
        Cell c = new Cell();
        Paragraph p = new Paragraph();
        Text t = new Text(text);
        c.addStyle(style);
        p.add(t);
        c.add(p);
        table.addCell(c);
    }
    
    public static void main(String[] args) throws FileNotFoundException {
        PdfWriter writer = new PdfWriter("C:\\Temp\\test.pdf");
        PdfDocument pdf = new PdfDocument(writer);
        try (Document document = new Document(pdf)) {
            Style style = new Style().setBold();
            Table table = new Table(UnitValue.createPercentArray(9));
            table.useAllAvailableWidth();
            table.setFixedLayout();
            
            makeCell(table, style, "Description");
            makeCell(table, style, "DescrIption"); /* Capital I */
            makeCell(table, style, "Description");
            makeCell(table, style, "Description");
            makeCell(table, style, "Description");
            makeCell(table, style, "DescrIption"); /* Capital I */
            makeCell(table, style, "Description");
            makeCell(table, style, "Description");
            makeCell(table, style, "Description");
            
            document.add(table);
        }
    }
}

结果- 带有“描述”的单元格不渲染,带有“描述”的单元格渲染。

标签: javaitext7

解决方案


这似乎是 iText 中的一个错误。

作为一种解决方法,您可以提供适当的粗体字体,而不是使用带有setBold(). 事实上,提供适当的粗体字体是使文本看起来粗体的推荐方法,因为粗体模拟在输出质量方面会产生较差的结果。

唯一的修改需要在您的Style对象中完成,因为您已经使用了样式以进行正确的重用!

Style style = new Style().setFont(PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD));

视觉结果:

结果


推荐阅读