使用iText XMLWorker在PdfPTable单元格内对齐文本

时间:2017-03-08 15:09:36

标签: java alignment itext xmlworker text-justify

我试图使用以下代码证明PdfPTable单元格内的文本:

                    PdfPTable pTable = new PdfPTable(1);
                    pTable.setWidthPercentage(98f);
                    pTable.setSpacingBefore(10f);
                    pTable.setHorizontalAlignment(Element.ALIGN_JUSTIFIED_ALL);

                    String content=getContent();

                    list =XMLWorkerHelper.parseToElementList(content);
                    for (Element element : list) {
                        cell = new PdfPCell();
                        cell.setHorizontalAlignment(PdfPCell.ALIGN_JUSTIFIED_ALL);
                        cell.setVerticalAlignment(PdfPCell.ALIGN_JUSTIFIED_ALL);
                        cell.setNoWrap(false);
                        cell.setBorderWidth(0);
                        cell.addElement(element);
                        pTable.addCell(cell);
                    }
                    pTable.setSplitLate(false);
                    paragraph.add(pTable);

但文字是左对齐的。我成功使用Paragraph对象而不是表格,但我需要在表格中显示文字。

1 个答案:

答案 0 :(得分:2)

.NET,但很容易转换为Java ...

由于您正在解析[X]HTML并使用XMLWorkerHelper,因此验证文本的一种简单方法是使用overloaded parseXHtml method并自行设置CSS样式。示例HTML:

<html><head>
<title>Test HTML</title>
<style type='text/css'>
td { 
    border:1px solid #eaeaea; 
    padding: 4px;
    text-align: right; 
    font-size: 1.4em; 
}
</style>
</head><body>
<table width='50%'><tr>
<td>
but I can not see justification of text. 
I tried using only paragraph without using table, 
and it does justification but I need to display 
things in table
</td></tr></table>
</body></html>

解析代码:

// CSS specificity selector: apply style below without changing existing styles
string css = "tr td { text-align: justify; }";

using (var memoryStream = new MemoryStream())
{
    using (var document = new Document())
    {
        PdfWriter writer = PdfWriter.GetInstance(
            document, memoryStream
        );
        document.Open();
        using (var htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(html)))
        {
            using (var cssStream = new MemoryStream(Encoding.UTF8.GetBytes(css)))
            {
                XMLWorkerHelper.GetInstance().ParseXHtml(
                    writer, document, htmlStream, cssStream
                );
            }
        }
    }
    File.WriteAllBytes(OUTPUT, memoryStream.ToArray());
}

请注意XMLWorkerHelper足够聪明,可以在调用ParseXHtml()时正确应用CSS Specificity个样式:

  1. <style>
  2. 中维护指定的样式
  3. 将文字对齐方式从right更改为justify
  4. 输出PDF:

    enter image description here