如何以编程方式打开受密码保护的PDF文件?

时间:2012-06-05 23:36:06

标签: c# .net pdf password-protection

Adob​​e IFilter不提供提供密码以打开受密码保护的PDF文件的机制,因此不能用于打开受密码保护的文件。

我想知道,是否有一种相对简单的方法以编程方式检索PDF文件中的实际加密数据,使用标准加密API对其进行解密,然后使用解密数据构建新的PDF文件?

2 个答案:

答案 0 :(得分:2)

如果您使用Spire PDF,那么您可以从加密的PDF中获取页面的图像,如下所示:

using System;
using System.Drawing;
using Spire.Pdf;
namespace PDFDecrypt
{
    class Decrypt
    {
        static void Main(string[] args)
        {
            //Create Document
            String encryptedPdf = @"D:\work\My Documents\Encryption.pdf";
            PdfDocument doc = new PdfDocument(encryptedPdf, "123456");

            //Extract Image
            Image image = doc.Pages[0].ImagesInfo[0].Image;

            doc.Close();

            //Save
            image.Save("EmployeeInfo.png", System.Drawing.Imaging.ImageFormat.Png);

            //Launch
            System.Diagnostics.Process.Start("EmployeeInfo.png");
        }
    }
}

答案 1 :(得分:2)

要打开受密码保护的PDF,您需要至少开发PDF解析器,解密器和生成器。不过,我不建议这样做。完成任务并不容易。

借助PDF库,一切都变得更加简单。您可能想尝试Docotic.Pdf library来完成任务(免责声明:我为图书馆的供应商工作)。

以下是您的任务示例:

public static void unprotectPdf(string input, string output)
{
    bool passwordProtected = PdfDocument.IsPasswordProtected(input);
    if (passwordProtected)
    {
        string password = null; // retrieve the password somehow

        using (PdfDocument doc = new PdfDocument(input, password))
        {
            // clear both passwords in order
            // to produce unprotected document
            doc.OwnerPassword = "";
            doc.UserPassword = "";

            doc.Save(output);
        }
    }
    else
    {
        // no decryption is required
        File.Copy(input, output, true);
    }
}

Docotic.Pdf也可以extract text (formatted or not) from PDFs。它可能对索引很有用(我想这是你要做的,因为你提到了Adobe IFilter)