我有一个包含3个字段的PDF文档txt_FirstName
,txt_MiddleName
并且txt_LastName
使用iTextSharp编写了该文档。
我有一个循环,用于创建输出文件,对其进行写入并关闭该文件。
在循环中,文件第一次写入名字和中间名。
在循环中第二次,文件应具有名字,中间名,并写上姓氏。
问题:问题是,当第二遍循环时,将姓氏写为名字,中间名消失了。
目标:我要做的主要事情是多次写入同一PDF文档
下载PDF模板: https ://www.scribd.com/document/412586469/Testing-Doc
public static string templatePath = "C:\\temp\\template.pdf";
public static string OutputPath = "C:\\Output\\";
private static void Fill_PDF()
{
string outputFile = "output.pdf";
int counter = 1;
for (int i = 0; i < 2; i++)
{
PdfStamper pdfStamper;
PdfReader reader;
reader = new PdfReader(File.ReadAllBytes(templatePath));
PdfReader.unethicalreading = true;
if (File.Exists(OutputPath + outputFile))
{
pdfStamper = new PdfStamper(reader, new FileStream(OutputPath + outputFile,
FileMode.Append, FileAccess.Write));
}
else
{
pdfStamper = new PdfStamper(reader, new FileStream(OutputPath + outputFile,
FileMode.Create));
}
AcroFields pdfFormFields = pdfStamper.AcroFields;
if (counter == 1)
{
pdfFormFields.SetField("txt_FirstName", "Scooby");
pdfFormFields.SetField("txt_MiddleName", "Dooby");
counter++;
}
else if (counter == 2)
{
pdfFormFields.SetField("txt_LastName", "Doo");
}
pdfStamper.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎是一个简单的错误。第一次执行循环时,您将加载空白模板并输入名字和中间名。第二次通过循环,您再次加载空白模板,并仅向其写入姓氏,然后保存为相同的文件名,并将其覆盖。如果在第二次循环中要加载已经包含名字和中间名的文件,则必须加载第一次编写的输出文件,而不是空白模板。或者,如果您想再次在if (counter == 2)
子句内部加载空白模板,则必须写所有3个名称,而不仅仅是姓氏。
我转载了您的错误,并使其正常工作。这是我描述的第一个解决方案的代码(对您的代码进行了微小的修改):
public static string templatePath = "C:\\temp\\template.pdf";
public static string OutputPath = "C:\\temp\\output\\";
private static void Fill_PDF()
{
string outputFile = "output.pdf";
int counter = 1;
for (int i = 0; i < 2; i++)
{
PdfStamper pdfStamper;
PdfReader reader = null;
/********** here's the changed part */
if (counter == 1)
{
reader = new PdfReader(File.ReadAllBytes(templatePath));
} else if (counter == 2)
{
reader = new PdfReader(File.ReadAllBytes(OutputPath + outputFile));
}
/************ end changed part */
PdfReader.unethicalreading = true;
if (File.Exists(OutputPath + outputFile))
{
pdfStamper = new PdfStamper(reader, new FileStream(OutputPath + outputFile,
FileMode.Append, FileAccess.Write));
}
else
{
pdfStamper = new PdfStamper(reader, new FileStream(OutputPath + outputFile,
FileMode.Create));
}
AcroFields pdfFormFields = pdfStamper.AcroFields;
if (counter == 1)
{
pdfFormFields.SetField("txt_FirstName", "Scooby");
pdfFormFields.SetField("txt_MiddleName", "Dooby");
counter++;
}
else if (counter == 2)
{
pdfFormFields.SetField("txt_LastName", "Doo");
}
pdfStamper.Close();
}
}
Run Code Online (Sandbox Code Playgroud)