且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何更新,而无需创建一个新的PDF PDF文件?

更新时间: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:

  • read the original file with PdfReader,
  • create a temporary file for PdfStamper, and when you're done,
  • replace the original file with the temporary file.

Or:

  • read the original file into a byte[],
  • create PdfReader with this byte[], and
  • use the path to the original file for PdfStamper.

This second option is more dangerous, as you'll lose the original file if you do something that causes an exception in PdfStamper.