Using itextsharp (or any c# pdf library), how to open a PDF, replace some text, and save it again?

后端 未结 3 421
孤城傲影
孤城傲影 2021-02-04 16:09

Using itextsharp (or any c# pdf library), i need to open a PDF, replace some placeholder text with actual values, and return it as a byte[].

Can someone suggest how to d

3条回答
  •  情深已故
    2021-02-04 16:37

    In the end, i used PDFescape to open my existing PDF file, and place some form fields in where i need to put my fields, then save it again to create my PDF file.

    http://www.pdfescape.com

    Then i found this blog entry about how to replace form fields:

    http://www.johnnycode.com/blog/2010/03/05/using-a-template-to-programmatically-create-pdfs-with-c-and-itextsharp/

    All works nicely! Here's the code:

    public static byte[] Generate()
    {
      var templatePath = HttpContext.Current.Server.MapPath("~/my_template.pdf");
    
      // Based on:
      // http://www.johnnycode.com/blog/2010/03/05/using-a-template-to-programmatically-create-pdfs-with-c-and-itextsharp/
      var reader = new PdfReader(templatePath);
      var outStream = new MemoryStream();
      var stamper = new PdfStamper(reader, outStream);
    
      var form = stamper.AcroFields;
      var fieldKeys = form.Fields.Keys;
    
      foreach (string fieldKey in fieldKeys)
      {
        if (form.GetField(fieldKey) == "MyTemplatesOriginalTextFieldA")
          form.SetField(fieldKey, "1234");
        if (form.GetField(fieldKey) == "MyTemplatesOriginalTextFieldB")
          form.SetField(fieldKey, "5678");
      }
    
      // "Flatten" the form so it wont be editable/usable anymore  
      stamper.FormFlattening = true;  
    
      stamper.Close();
      reader.Close();
    
      return outStream.ToArray();
    }
    

提交回复
热议问题