C# 在PDF中创建和填充域

2019-12-30 16:53:56于丽


//创建PDF文档
PdfDocument pdf = new PdfDocument();
//添加一个新页面
PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4, new PdfMargins());
//添加文本到页面
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 10f), true);
page.Canvas.DrawString("年龄:", font, PdfBrushes.DeepSkyBlue, 10, 50);
//创建文本域并指定文本域的名称
PdfTextBoxField textbox = new PdfTextBoxField(page, "Age");  
//设置文本域的大小、位置、字体
textbox.Bounds = new RectangleF(40, 50, 50, 12);  
textbox.Font = font;
//添加文本域到文档
pdf.Form.Fields.Add(textbox);
//保存文档
pdf.SaveToFile("Fields.pdf");

pdf填充域,C#区域填充,C#编辑PDF,C#,添加pdf编辑域

当然多数时候我们的需求可能不止是创建一个简单的文本域,还需要做一些其他设置,如设置边框、背景色、字体颜色、字体排列方式。甚至是指定文本域的输入内容,如只能输入日期或某一范围内的数字等。

设置格式:


//设置边框
textbox.BorderWidth = 0.75f;
textbox.BorderStyle = PdfBorderStyle.Solid;
textbox.BorderColor = Color.Black;
//设置背景色
textbox.BackColor = Color.Yellow;
//设置字体颜色
textbox.ForeColor = Color.Red;
//设置字体排列方式 
textbox.TextAlignment = PdfTextAlignment.Center;

pdf填充域,C#区域填充,C#编辑PDF,C#,添加pdf编辑域

指定文本域的输入内容:

Adobe Acrobat支持开发者使用Javascript来预先定义文本域输入内容的格式、类型等。该组件也支持这类script并提供了对应的方法来实现这些功能。下表列出了部分Javascript和方法:

 

描述

示例

Javascript

方法

Date

01/31/2008

AFDate_FormatEx("mm/dd/yyyy");
AFDate_KeystrokeEx("mm/dd/yyyy");

GetDateFormatString("mm/dd/yyyy");
GetDateKeystrokeString("mm/dd/yyyy");

Date

1/31/2008

AFDate_FormatEx("m/d/yyyy");
AFDate_KeystrokeEx("m/d/yyyy");

GetDateFormatString("m/d/yyyy");
GetDateKeystrokeString("m/d/yyyy");

Zip code

12345

AFSpecial_Format(0);
AFSpecial_Keystroke(0);

GetSpecialFormatString(0);
GetSpecialKeystrokeString(0);

Zip+4

12345-1234

AFSpecial_Format(1);
AFSpecial_Keystroke(1);

GetSpecialFormatString(1);
GetSpecialKeystrokeString(1);

Phone number

(123) 456-7890

AFSpecial_Format(2);
AFSpecial_Keystroke(2);

GetSpecialFormatString(2);
GetSpecialKeystrokeString(2);

Money

$12,345.00
  -$12,345.00

AFNumber_Format(2, 0, 0, 0,   "$", true);
AFNumber_Keystroke(2, 0, 0, 0, "$", true);

GetNumberFormatString(2, 0,   0, 0, "$", true);
GetNumberKeystrokeString(2, 0, 0, 0, "$", true);

Validate

1≤input value≤10

AFRange_Validate(true,1,true,10)

GetRangeValidateString(true,   1, true, 10);