VS2010下asp.net 對現有的PDF文件進行加密(利用iTextSharp)
到2011年8月iTextSharp最新版本下載地址:
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閱讀器左側的總頁數似乎有點問題,不影響使用。
有人解決的可以跟上。