Lock PDF against editing using iTextSharp

2019-03-15 21:46发布

问题:

I've created a C# program using iTextSharp for reading a PDF, appending social DRM content and then saving the file. How do I lock this new PDF against further editing?

I want the user to be able to view the file without entering a password and I don't mind select/copy operations but I do mind the ability to remove the social DRM.

回答1:

Encrypt your PDF document. Simple HTTP Handler working example to get you started:

<%@ WebHandler Language="C#" Class="lockPdf" %>
using System;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;

public class lockPdf : IHttpHandler {
  public void ProcessRequest (HttpContext context) {
    HttpServerUtility Server = context.Server;
    HttpResponse Response = context.Response;
    Response.ContentType = "application/pdf";
    using (Document document = new Document()) {
      PdfWriter writer = PdfWriter.GetInstance(
        document, Response.OutputStream
      );
      writer.SetEncryption(
// null user password => users can open document __without__ pasword
        null,
// owner password => required to __modify__ document/permissions        
        System.Text.Encoding.UTF8.GetBytes("ownerPassword"),
/*
 * bitwise or => see iText API for permission parameter:
 * http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfWriter.html
 */
        PdfWriter.ALLOW_PRINTING
            | PdfWriter.ALLOW_COPY
        , 
// encryption level also in documentation referenced above        
        PdfWriter.ENCRYPTION_AES_128
      );
      document.Open();
      document.Add(new Paragraph("hello world"));
    }
  }
  public bool IsReusable { get { return false; } }
}

Inline comments should be self-explanatory. See the PdfWriter documentation.

You can also encrypt a PDF document using a PdfReader object using the PdfEncryptor class. In other words, you can also do something like this (untested):

PdfReader reader = new PdfReader(INPUT_FILE);
using (MemoryStream ms = new MemoryStream()) {
  using (PdfStamper stamper = new PdfStamper(reader, ms)) {
    // add your content
  }
  using (FileStream fs = new FileStream(
    OUTPUT_FILE, FileMode.Create, FileAccess.ReadWrite))
  {
    PdfEncryptor.Encrypt(
      new PdfReader(ms.ToArray()),
      fs,
      null,
      System.Text.Encoding.UTF8.GetBytes("ownerPassword"),
      PdfWriter.ALLOW_PRINTING
          | PdfWriter.ALLOW_COPY,
      true
    );
  }  
}