c# – 使用iTextSharp锁定PDF以防编辑

我使用iTextSharp创建了一个C#程序,用于阅读PDF,附加社会DRM内容,然后保存文件.如何锁定这个新的PDF,进一步编辑?

我希望用户能够在不输入密码的情况下查看该文件,而我不介意选择/复制操作,但我记住删除社交DRM的能力.

解决方法

加密您的PDF文档.简单的HTTP处理程序工作示例让您开始:
<%@ 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; } }
}

内联评论应该是不言自明的.见PdfWriter documentation.

您还可以使用使用PdfEncryptor class的PdfReader对象加密PDF文档.换句话说,您还可以执行此操作(未测试):

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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...