使用iText 7(C#)创建删除线字体

问题描述 投票:0回答:1

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

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

但是我找不到任何关于如何1)使用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个回答
0
投票

我发现模仿删除线的唯一方法是使用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
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.