VS2010下asp.net 对现有的PDF文档进行加密(利用iTextSharp)

到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阅读器左侧的总页数似乎有点问题,不影响使用。

有人解决的可以跟上。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xjzdr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值