代码之家  ›  专栏  ›  技术社区  ›  Ahmad

使用Itext 7填写acro字段后,可编辑PDF变为不可编辑/只读

  •  1
  • Ahmad  · 技术社区  · 7 年前

    好的,我有这个PDF,它是一个可编辑的PDF,需要这样才能使用以下代码填写Acro字段:

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

    问题是,当它保存此文件的副本时,用户可以在获得PDF副本后轻松更改vlues。我们有没有办法在PDF填写表单后不保存可编辑的副本? 我四处看了看,很多pf的人说在PDF上添加加密密码,但这不是我这里的方法,我需要它开放给员工使用,当客户获得副本时,使其不可编辑,我正在使用最新版本的iText7。 谢谢是预付款。

    2 回复  |  直到 7 年前
        1
  •  2
  •   mkl    7 年前

    所以,只要用您需要的代码来回答这个问题,就像@mkl建议的那样使用flatte:下面是您可以做的

    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 
    

    这很容易做到,因为您可以在iText官方网站上看到这个答案: Flattening a form

        2
  •  0
  •   Joe Mayo    4 年前

    下面是我用来使PDF只读的代码 itext7 应用程序编程接口。可以在文档上设置两个密码, Owner User . 您可以将用户密码保留为 null 因此,任何用户都可以在没有任何密码限制的情况下打开它。这个 EncryptionConstants 类有多个字段,例如 ALLOW_SCREENREADER , ALLOW_COPY ALLOW_ASSEMBLY 等,可用于PDF权限限制。

    import com.itextpdf.kernel.pdf.PdfWriter;
    
    import com.itextpdf.kernel.pdf.PdfDocument;
    
    import com.itextpdf.kernel.pdf.EncryptionConstants;                                                                 
    
    import com.itextpdf.kernel.pdf. WriterProperties;                                                                        
    
    import com.itextpdf.layout.Document;
    
     
    
    final String OWNER_PASSWORD = "Security";
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
    WriterProperties wp = new WriterProperties();
    
    wp.setStandardEncryption(null, OWNER_PASSWORD.getBytes(), EncryptionConstants.ALLOW_PRINTING,EncryptionConstants.DO_NOT_ENCRYPT_METADATA);
    
    writer = new PdfWriter( baos, wp );
    
    PdfDocument pdfDocument = new PdfDocument(writer);
    
    Document document = new Document(pdfDocument);