How to add a form field to an existing pdf with itextsharp?

后端 未结 3 1143
有刺的猬
有刺的猬 2020-12-24 03:37

How to add a form field to an existing pdf with itextsharp?

I have an existing pdf document, I\'d like to add form fields to it without creating a copy and writing o

3条回答
  •  半阙折子戏
    2020-12-24 04:15

    I struggled with this for awhile so figured I'd post the Question & Answer

    Using the PdfStamper itext class is the key. (I guess this does make a copy but it's much cleaner than using the itext PdfCopy classes).

    public void AddFormFieldToExistingPDF( )
    {
        PdfReader reader = new PdfReader(@"c:\existing.pdf");
    
        FileStream out = new FileStream(@"C:\existingPlusFields.pdf", FileMode.Create, FileAccess.Write);
    
        PdfStamper stamp = new PdfStamper(reader, out);           
    
        PdfFormField field = PdfFormField.CreateTextField(stamp.Writer, false, false, 50);
    
        // set a field w/some position and size
        field.SetWidget(new iTextSharp.text.Rectangle(40, 500, 360, 530),
                PdfAnnotation.HIGHLIGHT_INVERT);
    
        field.SetFieldFlags(PdfAnnotation.FLAGS_PRINT);
        field.FieldName = "some_field";
    
        // add the field here, the second param is the page you want it on
        stamp.AddAnnotation(field, 1);                        
        stamp.Close();
    }
    

提交回复
热议问题