Lock PDF against editing using iTextSharp

ε祈祈猫儿з 提交于 2019-12-03 13:38:36

问题


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


来源:https://stackoverflow.com/questions/8419649/lock-pdf-against-editing-using-itextsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!