Element inside class CSS definition not applied us

2019-08-30 07:20发布

问题:

Update: ITextSharp 5.5.2 Supports this feature but previous version of ITextSharp do not.

Does ITextSharp 5.5.1 support Class Element CSS selectors? Such as

<style>
    .test td {
        border: 1px solid green;
    }
</style>

I'm getting a result like this

When it should be something like

If not how would I go about achieving the same results?

Using the following code I do not get the desired results.

byte[] bytes;
Document document = new Document();

using (var memoryStream = new MemoryStream())
using (var pdfWriter = PdfWriter.GetInstance(document, memoryStream))
{
    document.Open();
    XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, document, new StringReader(html));
    document.Close();
    bytes = memoryStream.ToArray();
}

return bytes;

Here is my full html for reference

<html>
<head>
<style>
    .test td {
        border: 1px solid green;
    }
</style>
</head>
<body>
<table class='test'>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>Peter</td>
    <td>Griffin</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>Lois</td>
    <td>Griffin</td>
    <td>$150</td>
  </tr>
  <tr>
    <td>Joe</td>
    <td>Swanson</td>
    <td>$300</td>
  </tr>
  <tr>
    <td>Cleveland</td>
    <td>Brown</td>
    <td>$250</td>
</tr>
</table>
</body>
</html>

回答1:

This is a strange question since the default implementation of XML Worker does exactly what you need. We have an HTML file table_css.html that is converted to html_table_3.pdf and we use nothing more than the basic XML Worker code: ParseHtmlTable3

You only need 5 lines to achieve the result shown in the screen shot:

public void createPdf(String file) throws IOException, DocumentException {
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    // step 3
    document.open();
    // step 4
    XMLWorkerHelper.getInstance().parseXHtml(writer, document,
            new FileInputStream(HTML));
    // step 5
    document.close();
}