如果您了解 PDF 格式的内部结构,这很容易!下面的代码与我在此处为不同类型的 PDF 注释编写的代码几乎相同。该页面将更详细地解释事情并为您提供一些参考。但基本上诀窍是遍历每个页面,然后遍历每个页面的注释(表单字段属于此类),然后查找设置了最大长度的文本字段并删除该限制。所有这些工作都是在一个只读PdfReader
对象上完成的,所以一旦我们完成了,我们需要再次循环并使用某种 a 将其写回PdfWriter
。
以下是针对 iTextSharp 5.2.1 的完整工作 C# 2010 WinForms 应用程序,它显示了所有这些。有关详细信息,请参阅代码中的注释。
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
var inputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
var outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "output.pdf");
//Setup some variables to be used later
PdfDictionary PageDictionary = default(PdfDictionary);
PdfArray Annots = default(PdfArray);
//Bind a reader to our input PDF
PdfReader R = new PdfReader(inputFile);
//Store the number of pages
int PageCount = R.NumberOfPages;
//Loop through each page remember that page numbers start at 1
for (int i = 1; i <= PageCount; i++) {
//Get the current page
PageDictionary = R.GetPageN(i);
//Get all of the annotations for the current page
Annots = PageDictionary.GetAsArray(PdfName.ANNOTS);
//Make sure we have something
if ((Annots == null) || (Annots.Length == 0)) { continue; }
//Loop through each annotation
foreach (PdfObject A in Annots.ArrayList) {
//Convert the itext-specific object as a generic PDF object
PdfDictionary AnnotationDictionary = (PdfDictionary)PdfReader.GetPdfObject(A);
//See if this annotation has a WIDGET which would be the UI implementation of a form field
if (!AnnotationDictionary.Get(PdfName.SUBTYPE).Equals(PdfName.WIDGET)) { continue; }
//See if this annotation is a text field (TX)
if (!AnnotationDictionary.Get(PdfName.FT).Equals(PdfName.TX)) { continue; }
//See if it has a maximum length specified (MAXLEN)
if (AnnotationDictionary.Contains(PdfName.MAXLEN)) {
//If so, remove it
AnnotationDictionary.Remove(PdfName.MAXLEN);
}
}
}
//Next we create a new document add import each page from the reader above
using (FileStream FS = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (Document Doc = new Document()) {
using (PdfCopy writer = new PdfCopy(Doc, FS)) {
Doc.Open();
for (int i = 1; i <= R.NumberOfPages; i++) {
writer.AddPage(writer.GetImportedPage(R, i));
}
Doc.Close();
}
}
}
}
}
}