c# - 使用 iText 7 (C#) 创建删除线字体
问题描述
我正在更新一个 C# 项目以使用iText 7,并希望为表单字段中设置的值添加删除线效果。该代码最初使用旧版本的iTextSharp,这使得创建删除线字体非常直观:
// older iTextSharp code
Font strikethruFont = new Font(normalBase, 11f, Font.STRIKETHRU);
但是,我找不到任何示例或文档说明如何 1)使用iText 7创建带有删除线的字体,如上所示,并在表单字段中使用它或 2)使用其他工具(PdfCanvas
、、对象Tables
等Text
)添加样式在设置它的值之前到表单字段。
// 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()
.
解决方案
我发现模仿删除线的唯一方法是使用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
推荐阅读
- lua - How to detect right-click on DCollapsibleCategory? [GLua]
- php - 为什么这个模态表单被重定向到我的 php 文件?
- shell - 如何在 AppShell Xamarin 表单中制作透明导航栏
- java - 当属性具有 @XmlJavaTypeAdapter 注释时,使用 Swagger/Springfox 更正数据类型
- java - OnClickListener 类不打开相机
- karate - 空手道平行赛跑者的问题
- r - 面向数据集
- objective-c - 在对数组或字典进行变异时,在目标 C 中的循环中编写 for 是否需要 __block 关键字?
- python-3.x - python3中的端口扫描器
- php - shell exec 命令在 mac 中不起作用。命令在终端上工作