I am currently using IText7 to convert a HTML file to PDF. Due to the nature of the app, each line of text in a paragraph is required to be stored on an individual line inside it's own div container, this causes issues justifying the paragraph as a whole. To get around this, I need to be able to manually measure the width of the div container, and then measure the width of the text content inside it, and then apply the justification based upon a ratio we decide.
The part I am struggling with, is how to measure the width of the elements mentioned above inside the IText pipeline. I've written a TagWorker which will fire when a div element with the "justify-text" attribute is detected, I was hoping I could override the ProcessEnd method, detect the width of the elements, and act appropriately, however I'm struggling to find out how. I can find the elements in question, but calculating the width is the issue.
iText 7: Paragraph height as it would be rendered
I've attempted to follow this article to do that, however I couldn't get this code to run, it errors with the following exception which I've failed to resolve.
System.InvalidOperationException: 'FontProvider and FontSet are empty. Cannot resolve font family name (see ElementPropertyContainer#setFontFamily) without initialized FontProvider (see RootElement#setFontProvider).'
Heres my code.
public JustifyWorker(IElementNode element, ProcessorContext context) : base(element, context)
{
}
public override void ProcessEnd(IElementNode element, ProcessorContext context)
{
base.ProcessEnd(element, context);
var result = (Div) this.GetElementResult();
var width = this.GetWidth(result, new Document(context.GetPdfDocument()).GetRenderer());
}
private float GetWidth(IElement prop, RootRenderer parentRenderer)
{
IRenderer renderer = prop.CreateRendererSubTree();
LayoutResult result = renderer.SetParent(parentRenderer).Layout(new LayoutContext(new LayoutArea(1, new Rectangle(100, 1000))));
return result.GetOccupiedArea().GetBBox().GetWidth();
}
}
Is the TagWorkers the correct place to do this? If so can anyone help me figure out how to get the width of the div element, and the text inside?