【问题标题】:Creating a strikethrough font with iText 7 (C#)使用 iText 7 (C#) 创建删除线字体
【发布时间】:2018-10-18 13:05:57
【问题描述】:

我正在更新一个 C# 项目以使用 iText 7,并希望为表单字段中设置的值添加删除线效果。该代码最初使用旧版本的 iTextSharp,这使得创建删除线字体变得相当直观:

// older iTextSharp code
Font strikethruFont = new Font(normalBase, 11f, Font.STRIKETHRU);

但是我找不到任何示例或文档说明如何 1) 使用 iText 7 创建带有删除线的字体,如上面的 iText 7 并在表单字段中使用它或 2) 使用其他工具(PdfCanvasTablesText 对象等)在设置其值之前向表单字段添加样式。

// somehow create a strikethrough font
PdfFont strikethruFont = ???

PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);

form.GetField("Some Field Name")
    .SetValue("Some content to strike through", strikethruFont, 11f)

注意:我已经看到使用 Text 对象然后用负 y 偏移为它加下划线的示例(有效地将下划线拉到文本区域,模仿删除线)。不幸的是,Text 对象不能与 form.SetValue() 一起使用。

【问题讨论】:

    标签: c# pdf itext pdf-generation itext7


    【解决方案1】:

    我发现模仿删除线的唯一方法是使用 PdfCanvas 对象在 PDF 上画线。这不是一个干净的方法,我希望 iText7 的人会努力改进他们的文档,但我会在此处包含我的解决方法,希望它可以帮助解决类似问题的人。

    // set the form field value per normal
    form.GetField(fieldName)
        .SetValue(fieldValue);
    
    // draw a line exactly in the middle of the form field
    Rectangle fieldFormArea = form.GetField(fieldName)
                                  .GetWidgets()
                                  .First()
                                  .GetRectangle()
                                  .ToRectangle();
    
    float fieldWidth = fieldFormArea.GetWidth();
    float fieldHeight = fieldFormArea.GetHeight();
    float bottomLeftX = fieldFormArea.GetX();
    float bottomLeftY = fieldFormArea.GetY();
    
    PdfCanvas canvas = new PdfCanvas(form.GetPdfDocument().GetFirstPage());
    
    // Approach A: put a line through the whole width of the field
    canvas.MoveTo(bottomLeftX, bottomLeftY + (fieldHeight / 2));
    canvas.LineTo(bottomLeftX + fieldWidth, bottomLeftY + (fieldHeight / 2))
          .SetLineWidth(0.75f)
          .ClosePathStroke();
    
    // Approach B: put a line that covers just the text in the field
    PdfFont font = PdfFontFactory.CreateFont(FontConstants.TIMES_ROMAN);
    PdfString content = new PdfString(fieldValue);
    // assumes size 11 text
    float textWidth = (font.GetContentWidth(content) * 11) / 1000.0f;
    
    // then use textWidth in place of fieldWidth in Approach A above
    

    【讨论】:

      猜你喜欢
      • 2019-01-11
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      相关资源
      最近更新 更多