iTextSharp GetFieldPositions to SetSimpleColumn

2019-01-27 02:23发布

问题:

I'm using the latest version of iTextSharp found here: http://sourceforge.net/projects/itextsharp/

I am trying to use ColumnText.SetSimpleColumn after getting the position of some AcroFields using GetFieldPositions( fieldName ).

All the examples I can find show GetFieldPositions returning a float[] however this doesn't appear to be the case anymore. It now appears to be returning IList which doesn't (according to Visual Studio) implicitly convert to a float[].

Inside the return value at the 0 index is a position member that is a Rectangle, but since the examples I've seen perform math operations on the returned float[] I'm not sure what values from the return value in GetFieldPostions to use when using SetSimpleColumn. Here's one article that I'm referencing: http://blog.dmbcllc.com/2009/07/08/itextsharp-html-to-pdf-positioning-text/

Simplest accepted answer will be how to translate the value from GetFieldPositions to SetSimpleColumn.

Thanks!

回答1:

I think this was done for two reasons. 1), GetFieldPositions() could actually return multiple items because you can technically have more than one field with the same name and 2), the original array method required knowing "magic array numbers" to find what was what. All of the code that you saw pretty much assumed that GetFieldPositions() only returned a single item, which is true 99% of the time. Instead of working with indexes you can now work with normal properties.

So the code from the link that you posted:

float[] fieldPosition = null;
fieldPosition = fields.GetFieldPositions("fieldNameInThePDF");
left = fieldPosition[1];
right = fieldPosition[3];
top = fieldPosition[4];
bottom = fieldPosition[2];
if (rotation == 90)
{
    left = fieldPosition[2];
    right = fieldPosition[4];
    top = pageSize.Right - fieldPosition[1];
    bottom = pageSize.Right - fieldPosition[3];
}

Should be converted to:

IList<AcroFields.FieldPosition> fieldPositions = fields.GetFieldPositions("fieldNameInThePDF");
if (fieldPositions == null || fieldPositions.Count <= 0) throw new ApplicationException("Error locating field");
AcroFields.FieldPosition fieldPosition = fieldPositions[0];
left = fieldPosition.position.Left;
right = fieldPosition.position.Right;
top = fieldPosition.position.Top;
bottom = fieldPosition.position.Bottom;
if (rotation == 90)
{
    left = fieldPosition.position.Bottom;
    right = fieldPosition.position.Top;
    top = pageSize.Right - fieldPosition.position.Left;
    bottom = pageSize.Right - fieldPosition.position.Right;
}