how can a password-protected PDF file be opened programmatically?

笑着哭i 提交于 2019-12-01 12:03:11

To open a password protected PDF you will need to develop at least a PDF parser, decryptor and generator. I wouldn't recommend to do that, though. It's nowhere near an easy task to accomplish.

With help of a PDF library everything is much simpler. You might want to try Docotic.Pdf library for the task (disclaimer: I work for the vendor of the library).

Here is a sample for you task:

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 can also extract text (formatted or not) from PDFs. It might be useful for indexing (I guess it's what you are up to because you mentioned Adobe IFilter)

If you use SpirePDF then you can get images of the pages out of an ecrypted PDF like this:

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");
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!