为什么我不能将包含PdfPTable
的{{1}}写入现有PDF? iTextSharp告诉我
在此上下文中不受支持。使用
PdfFormField
。
PdfStamper.addAnnotation()
答案 0 :(得分:0)
iTextSharp类FieldPositioningEvents
只能在将基础PdfWriter
与PdfDocument
实例结合使用时从头开始创建新PDF,因为它使用writer.addAnnotation(field)
/ fieldWriter.addAnnotation(cellField)
调用在标记上下文中不受支持。
要解决此限制,只需创建自己的单元格事件侦听器,该侦听器使用addAnnotation
重载,并在PdfStamper
中显示页码。
(不幸的是,我在本世纪尚未完成任何VB编码;但我希望,C#中的示例也可以提供帮助。)
E.g。以下是从原始FieldPositioningEvents
代码派生的事件监听器,但仅限于单元格事件并适用于PdfStamper
:
public class StampingFieldPositioningEvents : IPdfPCellEvent
{
/** Keeps the form field that is to be positioned in a cellLayout event. */
protected PdfFormField cellField = null;
/** The PdfStamper to use when a field has to added in a cell event. */
protected PdfStamper fieldStamper = null;
/** Some extra padding that will be taken into account when defining the widget. */
public float padding;
/** The page on which the field is added */
int fieldPage = 0;
/** Creates a new event. This constructor will be used if you need to position fields with a Cell Event. */
public StampingFieldPositioningEvents(PdfStamper stamper, PdfFormField field, int page)
{
this.cellField = field;
this.fieldStamper = stamper;
this.fieldPage = page;
}
/** Creates a new event. This constructor will be used if you need to position fields with a Cell Event. */
public StampingFieldPositioningEvents(PdfStamper stamper, String text, int page)
{
this.fieldStamper = stamper;
TextField tf = new TextField(stamper.Writer, new Rectangle(0, 0), text);
tf.FontSize = 14;
cellField = tf.GetTextField();
this.fieldPage = page;
}
/** The padding to set. */
virtual public float Padding
{
set
{
padding = value;
}
get
{
return padding;
}
}
/** IPdfPCellEvent implementation */
virtual public void CellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] canvases)
{
cellField.Put(PdfName.RECT, new PdfRectangle(rect.GetLeft(padding), rect.GetBottom(padding), rect.GetRight(padding), rect.GetTop(padding)));
fieldStamper.AddAnnotation(cellField, fieldPage);
}
}
它的使用方式类似于OP的原始代码:
PdfReader reader = new PdfReader(SOURCE);
PdfStamper stamper = new PdfStamper(reader, new FileStream(DESTINATION, FileMode.Create));
int pageMargin = 20;
PdfPTable table = new PdfPTable(1);
table.TotalWidth = reader.GetPageSize(1).Width - 40;
PdfFormField formField = PdfFormField.CreateTextField(stamper.Writer, false, false, 50);
formField.SetWidget(new Rectangle(0, 0), null);
formField.FieldName = "TestField";
PdfPCell tbCell = new PdfPCell
{
CellEvent = new StampingFieldPositioningEvents(stamper, formField, 1),
MinimumHeight = 10,
BorderWidth = 0.1f
};
table.AddCell(tbCell);
table.WriteSelectedRows(0, -1, reader.GetPageSize(1).Left + pageMargin, reader.GetPageSize(1).Bottom + table.TotalHeight + pageMargin, stamper.GetOverContent(1));
stamper.Close();
reader.Close();