How to update a PDF without creating a new PDF?

有些话、适合烂在心里 提交于 2019-11-26 02:26:33

问题


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();

                }

            }
        }

回答1:


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.



来源:https://stackoverflow.com/questions/16081831/how-to-update-a-pdf-without-creating-a-new-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!