Search code examples
c#asp.netpdf-generationitext7

editable PDF to Non-Editable/Read Only after filling in the acro-fields using Itext 7


Ok so I have this PDF that's a Edit-able PDF that needs to be like that to be able to fill in the Acro-Fields using this code:

   string src = @"C:\Test.pdf";
        string dest = @"C:\TestDone.pdf";
        PdfReader reader = new PdfReader(src);

        reader.SetUnethicalReading(true);
        PdfDocument pdfDoc = new PdfDocument(reader, new PdfWriter(dest)); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
        IDictionary<String, PdfFormField> fields = form.GetFormFields();
        PdfFormField toSet;
 fields.TryGetValue("Name", out toSet);
                toSet.SetValue(NameString);

The problem is when it saves the copy of this its still edit able the user can easily change the vlues after the PDF copy they get. Is there a way we could have this to save no-editable copy of the PDF after it fills in the form? I looked around and a lot pf people says add the Encrypted Pass word on the PDF but that's not the approach I have here I need it to be open for the use of the employees and when the Client gets the copy make it No-Editable I am using iText7 the latest version. Thanks is Advance.


Solution

  • So just to answer this question with the Code that you need to get this done Like @mkl suggested use flatten: here is what you could do

    string src = @"C:\Test.pdf";
    string dest = @"C:\TestDone.pdf";
    
    PdfReader reader = new PdfReader(src);
    reader.SetUnethicalReading(true);
    PdfDocument pdfDoc = new PdfDocument(reader, new PdfWriter(dest)); 
    
    PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
    IDictionary<String, PdfFormField> fields = form.GetFormFields();
    PdfFormField toSet;
    fields.TryGetValue("Name", out toSet);
    toSet.SetValue(NameString);
    
    PdfAcroForm.GetAcroForm(pdfDoc, true).FlattenFields(); // Add this line 
    

    This is very easy to do so as you could see this answer was found on iText Official Site: Flattening a form