1

I am trying to justify the text inside a PdfPTable cell with the following code:

                    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);

But the text is left aligned. I was successful using a Paragraph object instead of a table, but I need to display text in a table.

kuujinbo
  • 9,272
  • 3
  • 44
  • 57
Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91

1 Answers1

2

.NET, but easily converted to Java...

Since you're parsing [X]HTML and using XMLWorkerHelper, a simple way to justify the text is to use the overloaded parseXHtml method and set the CSS style yourself. Sample 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>

Parsing code:

// 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());
}

Note that XMLWorkerHelper is smart enough to apply the CSS Specificity styles correctly when calling ParseXHtml():

  1. Maintains specified styles in <style>.
  2. Changes text alignment from right to justify.

Output PDF:

enter image description here

kuujinbo
  • 9,272
  • 3
  • 44
  • 57