到2011年8月iTextSharp最新版本下载地址:
http://download.csdn.net/source/3514917
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Diagnostics;
//加密代码
protected void Button1_Click(object sender, EventArgs e)
{
string PdfPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
PdfPath = PdfPath + "PDFFiles\\";
string PdfFIle = PdfPath + "008.PDF";
string sname = PdfFIle;//要加密的文件
string sname1 = PdfPath + "test.PDF";//加密后生成的文件
PdfReader reader = new PdfReader(sname);
int n = reader.NumberOfPages;
Document document = new Document(reader.GetPageSizeWithRotation(1));
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(sname1, FileMode.Create));
writer.SetEncryption(PdfWriter.STRENGTH128BITS, "123456", null, PdfWriter.AllowPrinting);
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
int i = 0;
// step 4: we add content
while (i < n)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
//
// step 5: we close the document
document.Close();
writer.Close();
}
说明:加密后的文件没有访问,但PDF阅读器左侧的总页数似乎有点问题,不影响使用。
有人解决的可以跟上。