我正在使用以下代码删除旧的PDF并用新的PDF替换旧的PDF但没有结果。是否可以对PDF文件执行此操作?因为,在整个网络中,我看到这些函数用于.txt,.xls.doc ...等文件类型。我的代码有什么问题吗?请帮忙......
private void ListFieldNames(string s)
{
try
{
string pdfTemplate = @"z:\TEMP\PDF\PassportApplicationForm_Main_English_V1.0.pdf";
//var newFile = pdfTemplate;
string newFile = @"z:\TEMP\PDF\_PassportApplicationForm_Main_English_V1.0.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
//ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
PdfReader reader = new PdfReader((string)pdfTemplate);
//PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create));
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create)))
{
AcroFields form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
foreach (string fieldKey in fieldKeys)
{
//Replace Address Form field with my custom data
if (fieldKey.Contains("Surname"))
{
form.SetField(fieldKey, s);
}
}
// set form fields
//form.SetField("Address", s);
stamper.FormFlattening = true;
stamper.Close();
}
}
File.Copy(newFile, pdfTemplate);
File.Delete(pdfTemplate);
}
答案 0 :(得分:1)
一切看起来都不错,只需改变:
File.Copy(newFile, pdfTemplate);
File.Delete(pdfTemplate);
更改为:
File.Delete(pdfTemplate);
File.Copy(newFile, pdfTemplate);
如果文件在其位置上已存在且名称与文件同名,则无法复制该文件。 首先删除现有文件。