更新时间:2023-09-20 14:17:04
正如我在书中的 iText的行动,则无法读取文件的同时写入。想想Word如何工作的:你不能打开一个Word文档并直接写入。 Word总是创建一个临时文件,写入更改,然后替换它原来的文件,然后扔掉的临时文件。
您可以做到这一点:
PdfReader
原始文件, PdfStamper
的临时文件,当您完成后,或者
字节[]
, PdfReader
本字节[]
和 PdfStamper
。这第二个选项是比较危险的,因为如果你做一些事情,导致异常的 PdfStamper
你会失去原始文件。
I am required to replace a word in an existing PDF AcroField with another word. I am using PDFStamper of iTEXTSHARP to do the same and it is working fine. But, in doing so it is required to create a new PDF and i would like the change to be reflected in the existing PDF itself. If I am setting the destination filename same as the original filename then no change is being reflected.I am new to iTextSharp , is there anything I am doing wrong? Please help.. I am providing the piece of code I am using
private void ListFieldNames(string s)
{
try
{
string pdfTemplate = @"z:\TEMP\PDF\PassportApplicationForm_Main_English_V1.0.pdf";
string newFile = @"z:\TEMP\PDF\PassportApplicationForm_Main_English_V1.0.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
PdfReader reader = new PdfReader((string)pdfTemplate);
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create, FileAccess.ReadWrite)))
{
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("Address"))
{
form.SetField(fieldKey, s);
}
}
stamper.FormFlattening = true;
stamper.Close();
}
}
}
As documented in my book iText in Action, you can't read a file and write to it simultaneously. Think of how Word works: you can't open a Word document and write directly to it. Word always creates a temporary file, writes the changes to it, then replaces the original file with it and then throws away the temporary file.
You can do that too:
PdfReader
,PdfStamper
, and when you're done,Or:
byte[]
,PdfReader
with this byte[]
, andPdfStamper
.This second option is more dangerous, as you'll lose the original file if you do something that causes an exception in PdfStamper
.