2

I use itextsharp for creating a pdf. I need to place XHTML on it so I uase the XMLWorkerHelper class:

iTextSharp.tool.xml.XMLWorkerHelper worker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
worker.ParseXHtml(pdfWrite, doc, new StringReader(sb.ToString()));

However I would like to specify a position for the parsed XHTML. How do I do that?

EDIT:

I thought I will post the code in the case someone else runs into this. The link provided below was for JAVA and in C# things work a bit different.

First you need a class for gathering the Elements:

class ElementHandlerClass : iTextSharp.tool.xml.IElementHandler
{
    public List<IElement> elements = new List<IElement>();

    public void Add(iTextSharp.tool.xml.IWritable input)
    {
        if (input is iTextSharp.tool.xml.pipeline.WritableElement)
        {
            elements.AddRange(((iTextSharp.tool.xml.pipeline.WritableElement)input).Elements());
        }
    }
}

Then you use it

 ElementHandlerClass ehc = new ElementHandlerClass();
 worker.ParseXHtml(ehc, new StringReader(sb.ToString()));

Now you have the elements. Next step is to create a ColumnText and fill it with the Elements:

iTextSharp.text.pdf.ColumnText ct = new iTextSharp.text.pdf.ColumnText(pdfWrite.DirectContent);
ct.SetSimpleColumn(200, 300, 300, 500);
foreach (IElement element in ehc.elements)
     ct.AddElement(element);
ct.Go();
Peter Hans
  • 73
  • 6
  • Thank you for providing the syntax in C#. This will certainly help for further reference. I always have difficulties translating my answers from Java to C#, so it helps when somebody provides feedback on my Java answers in the form of working C# code. – Bruno Lowagie Dec 15 '14 at 09:23

1 Answers1

0

You need to combine the answers of two previous questions on StackOverflow.

The first answer you need, is the one to How to get particular html table contents to write it in pdf using itext

In this answer, you learn how to parse an XHTML source into a list of Element objects.

Once you have this list, you need the answer to itext ColumnText ignores alignment

You can create a ColumnText object, define a rectangle with the setSimpleColumn() method, add all the elements retrieved from the XHTML using XML Worker with the addElement() method, and go() to add that content.

Community
  • 1
  • 1
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165