Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Itext 获取多行字段的行数_Itext_Multiline_Pad_Acrofields - Fatal编程技术网

Itext 获取多行字段的行数

Itext 获取多行字段的行数,itext,multiline,pad,acrofields,Itext,Multiline,Pad,Acrofields,我有一个带有AcroFields的PDF。有些字段是多行字段。我需要用给定的文本填充字段,并用“*”(或预定义的字符/字符串)填充字段中的任何剩余空间。我可以使用iText添加文本,但不知道如何计算要添加的正确填充量 你能建议我怎么做吗。多谢各位 我写的代码是: public string CreatePdf(IDictionary<FieldKey, string> dictionary, string template, string saveAs) { // C

我有一个带有AcroFields的PDF。有些字段是多行字段。我需要用给定的文本填充字段,并用“*”(或预定义的字符/字符串)填充字段中的任何剩余空间。我可以使用iText添加文本,但不知道如何计算要添加的正确填充量

你能建议我怎么做吗。多谢各位

我写的代码是:

 public string CreatePdf(IDictionary<FieldKey, string> dictionary, string template, string saveAs)
 {
      // Create new PDF from template
      using (PdfReader reader = new PdfReader(template))
      using (FileStream stream = new FileStream(saveAs, FileMode.Create, FileAccess.ReadWrite))
      using (PdfStamper stamper = new PdfStamper(reader, stream))
      {
          // Populate PDF fields from dictionary
          AcroFields formFields = stamper.AcroFields;
          foreach (KeyValuePair<FieldKey, string> dataField in dictionary)
          {
              switch (dataField.Key.FieldType)
              {
                  case FieldType.Text:              
                  string fieldValue = dataField.Value;
                  // Add filler if a filler is set
                  if (!String.IsNullOrWhiteSpace(dataField.Key.FillRight))
                  {
                      fieldValue = GetTextWithFiller(formFields, dataField.Key.FieldName, fieldValue, dataField.Key.FillRight);
                  }
                  // Text field
                  if (!formFields.SetField(dataField.Key.FieldName, fieldValue))
                      throw new InvalidDataException(String.Format("Invalid Template Field: {0} in Template: {1}", dataField.Key.FieldName, template));
                  break;
                  case FieldType.Image:
                      // Image field
                      PlaceImage(formFields, dataField);
                      break;
                  case FieldType.Barcode2Of5:
                      // 2 of 5 Barcode
                      PlaceBarcode2Of5(dataField.Value, stamper);
                      break;
                  case FieldType.Barcode128:
                      // 2 of 5 Barcode
                      PlaceBarcode128(dataField.Value, stamper);
                      break;
                  default:
                      throw new InvalidDataException(String.Format("Invalid data filed type : {0}", dataField.Key.FieldType));
              }
          }
          // Save PDF
          reader.RemoveUnusedObjects();
          stamper.FormFlattening = true;
          stamper.Close();
      }
      return saveAs;
  }
publicstringcreatepdf(IDictionary字典、字符串模板、字符串另存为)
{
//从模板创建新的PDF
使用(PDF阅读器=新PDF阅读器(模板))
使用(FileStream stream=newfilestream(saveAs、FileMode.Create、FileAccess.ReadWrite))
使用(PdfStamper压模=新PdfStamper(读卡器,流))
{
//从字典填充PDF字段
AcroFields formFields=stamper.AcroFields;
foreach(字典中的KeyValuePair数据字段)
{
开关(dataField.Key.FieldType)
{
案例字段类型。文本:
字符串fieldValue=数据字段.Value;
//如果设置了填充,则添加填充
if(!String.IsNullOrWhiteSpace(dataField.Key.FillRight))
{
fieldValue=GetTextWithFiller(formFields,dataField.Key.FieldName,fieldValue,dataField.Key.FillRight);
}
//文本字段
如果(!formFields.SetField(dataField.Key.FieldName,fieldValue))
抛出新的InvalidDataException(String.Format(“模板{1}中的无效模板字段:{0}”,dataField.Key.FieldName,Template));
打破
案例字段类型。图像:
//图像场
PlaceImage(表单字段、数据字段);
打破
case FieldType.Barcode2Of5:
//第2页,共5页条形码
PlaceBarcode2Of5(数据字段.Value,压模);
打破
案例FieldType.Barcode128:
//第2页,共5页条形码
PlaceBarcode128(dataField.Value,压模);
打破
违约:
抛出新的InvalidDataException(String.Format(“无效数据字段类型:{0}”,dataField.Key.FieldType));
}
}
//保存PDF
reader.RemoveUnusedObjects();
stamper.FormFlatting=真;
压模关闭();
}
返回saveAs;
}
以及获取填充物的方法,该方法不符合我的预期:

private static string GetTextWithFiller(AcroFields fields, string fieldName, string text, string filler)
{        
    // Get the size of the rectangle that defines the field
    AcroFields.FieldPosition fieldPosition = fields.GetFieldPositions(fieldName)[0];
    Rectangle rect = fieldPosition.position;
    // Get field font
    PdfDictionary merged = fields.GetFieldItem(fieldName).GetMerged(0);
    TextField textField = new TextField(null, null, null);
    fields.DecodeGenericDictionary(merged, textField);
    Font fieldFont = new Font(textField.Font);
    Chunk whatWeHave = new Chunk(text, fieldFont);
    float textWidth = whatWeHave.GetWidthPoint();
    // See how far the text field is filled with give text
    float textEndPoint = rect.Left + textWidth;
    float rectBottom = rect.Bottom;
    float rectRight = rect.Right;
    float rectTop = rect.Top;
    // How many rows to fill
    int textRows = Convert.ToInt32(rect.Height / fieldFont.CalculatedSize);
    float totalCharactersWeCanFit = rect.Width * textRows;
    if (textWidth < totalCharactersWeCanFit)
        {
        // Get the width of filler character
        Chunk fillCharWidth = new Chunk(filler, fieldFont);
        // Available gap
        float gap = totalCharactersWeCanFit - textWidth;
        // How much filler required
        int fillAmount = Convert.ToInt32(gap / fillCharWidth.GetWidthPoint());
        // Fill with filler
        StringBuilder tempString = new StringBuilder();
        tempString.Append(text);
        for (int n = 0; n < fillAmount; ++n)
        {
            tempString.Append(filler);
        }
        text = tempString.ToString();
    }
    return text;
}
私有静态字符串GetTextWithFiller(AcroFields、string fieldName、string text、string filler)
{        
//获取定义字段的矩形的大小
AcroFields.FieldPosition FieldPosition=fields.GetFieldPositions(fieldName)[0];
矩形矩形矩形=fieldPosition.position;
//获取字段字体
PdfDictionary merged=fields.GetFieldItem(fieldName).GetMerged(0);
TextField TextField=新的TextField(null,null,null);
字段。DecodeGenericDictionary(合并,文本字段);
Font fieldFont=新字体(textField.Font);
Chunk whatWeHave=新块(文本、字段字体);
float textWidth=whatWeHave.GetWidthPoint();
//查看文本字段被给定文本填充的距离
float textEndPoint=rect.Left+textWidth;
浮动矩形底部=矩形底部;
float rectRight=rect.Right;
浮动矩形顶部=矩形顶部;
//要填充多少行
int textRows=Convert.ToInt32(rect.Height/fieldFont.CalculatedSize);
float TotalCharactersWebFit=矩形宽度*文本行;
if(文本宽度<总字符宽度)
{
//获取填充字符的宽度
Chunk fillCharWidth=新块(填充符,fieldFont);
//可用间隙
浮动间隙=总字符宽度-文本宽度;
//需要多少填料
int fillAmount=Convert.ToInt32(gap/fillCharWidth.GetWidthPoint());
//填充填料
StringBuilder tempString=新建StringBuilder();
tempString.Append(文本);
对于(int n=0;n
考虑一个包含三个多行文本字段的表单:

对于第一个字段,我们定义了字体大小0(这也是您要做的);对于第二个字段,我们定义字体12;对于第三个字段,我们定义了字体6

现在让我们填写并展平表格:

public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    AcroFields form = stamper.getAcroFields();
    StringBuilder sb = new StringBuilder();
    for (String name : form.getFields().keySet()) {
        int n = getInformation(form, name);
        for (int i = 0; i < n; i++) {
            sb.append(" *");
        }
        String filler = sb.toString();
        form.setField(name, name + filler);
    }
    stamper.setFormFlattening(true);
    stamper.close();
    reader.close();
}
首先,我们获取字体,以便创建
BaseFont
对象。然后我们得到字体大小,并使用存储在
BaseFont
中的信息,我们将定义用于计算前导的因子(即两行之间的间距)

我们还要求字段提供其尺寸。然后,我们计算可以将多少行放入字段矩形的高度(
),以及将
字符串“*”
放入字段矩形的宽度(
)的次数。如果我们将
相乘,我们将得到一个近似值,即我们必须添加
“*”
多少次才能得到合适的填充。无论我们是否有太多的填充物:如果定义了字体,所有不适合的文本都将被删除

您可以在这里找到完整的示例:

我们采用以下形式,
getInformation()
方法返回以下信息:

Basefont: Helvetica
Size: 0.0
Basefont: Helvetica
Size: 6.0
height: 86.0; width: 108.0
rows: 13; columns: 27
Basefont: Helvetica
Size: 12.0
height: 86.0; width: 107.999985
rows: 7; columns: 14
因为字体大小为0,所以我们无法告诉您关于第一个字段的更多信息。你的例子也是如此。如果字体为0,则无法回答您的问题。您无法计算该字段适合多少个
*
,因为您不知道将用于呈现
*
的字体大小

如果字体大小是12,我们可以容纳7行和14列(我们看到7行a)
Basefont: Helvetica
Size: 0.0
Basefont: Helvetica
Size: 6.0
height: 86.0; width: 108.0
rows: 13; columns: 27
Basefont: Helvetica
Size: 12.0
height: 86.0; width: 107.999985
rows: 7; columns: 14