Search code examples
c#itextxmlworker

iTextSharp XMLWorker Footer from html


I searched everywhere for this problem and I still can't get the working solution wrrr, it's very annoying.

I use xmlworker (itextsharp 2.1) to create pdf from html. This works perfectly to me, but I need to add footer and header to each page filled by piece of passed html. In example I have this string passed to function as footer html

<table>
    <tr>
        <td>كند / źćąśęłżźń</td>
        <td>something</td>
        <td><img src="i_03_x2.png"/></td>
    </tr>
</table>

And I need to parse it to list using XMLWorker.GetInstance() and add it as footer:

public override void OnEndPage(PdfWriter writer, Document document)
{
    PdfPTable footerTable = new PdfPTable(1);
    footerTable.TotalWidth = width;
    PdfPCell singleCell = new PdfPCell();
    singleCell.BorderWidth = 2f;

    DirectHandler handler = new DirectHandler();
    using (TextReader sr = new StringReader(HTMLtoPDF.footer.HTML))
    {
        XMLWorkerHelper.GetInstance().ParseXHtml(handler, sr);
    }

    foreach (var element in handler.elements)
    {
        singleCell.AddElement(element);
    }

    footerTable.AddCell(singleCell);
    footerTable.WriteSelectedRows(0, -1, left, bottom, writer.DirectContent);
}

public class DirectHandler : IElementHandler
{
    public List<IElement> elements = new List<IElement>();
    public void Add(IWritable w)
    {
        if (w is WritableElement)
        {
            elements.AddRange(((WritableElement)w).Elements());
        }
    }
}

And now Second and Third column from html shows but the first one is missing, so my question is:

Is it possible to attach my font (unicode arial) to

XMLWorkerHelper.GetInstance().ParseXHtml 

using my handler and font? ParseXHtml function has multiple overloads but I need to use necessarily DirectHandler as IElement handler and MY FONT (arialuni.ttf) as font provider. Any help would be appreciated


Solution

  • Ok, I figured this out, first - I need to completely resigned from ParseXHtml function. I used standard XMLWorker with this pipeline:

    PdfWriterPipeline pdf = new ElementHandlerPipeline(handler, null)
    

    Instead of default one:

    PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
    

    Then I was able to iterate through elements in handler

    foreach (var element in handler.elements)
    {
        singleCell.AddElement(element);
    }
    
    footerTable.AddCell(singleCell);