使用PDFsharp打开受密码保护的PDF

时间:2016-05-03 10:00:03

标签: c# wpf pdf pdfsharp

在我的程序中,我用我指定的密码写出PDF。这很重要,因为我知道我试图打开的PDF的密码(不是黑客或任何东西)。我这样密码保护PDF;

Application.Current.Dispatcher.InvokeAsync(new Action(() =>
{
    string sourcePath = sourceFilePath;
    string targetPath = @"C:\ExamplePath";

    useReturnedOHPath = true;

    string sourceFile = Path.Combine(sourcePath, fileName);

    var document = PdfReader.Open(sourceFile);
    var securitySettings = document.SecuritySettings;
    securitySettings.UserPassword = "ExamplePass";

    securitySettings.PermitAccessibilityExtractContent = false;
    securitySettings.PermitAnnotations = false;
    securitySettings.PermitAssembleDocument = false;
    securitySettings.PermitExtractContent = false;
    securitySettings.PermitFormsFill = true;
    securitySettings.PermitFullQualityPrint = false;
    securitySettings.PermitModifyDocument = true;
    securitySettings.PermitPrint = false;

    document.Save(sourceFile);
    MessageBox.Show(sourceFile);

    string cleanPath = CleanFileName(selectedPerson.ID + " " + DateTime.Now.ToString("dd-MM-yyyy hh-mm-ss") + ".pdf");
    ohDestFile = Path.Combine(targetPath, cleanPath);

    File.Copy(sourceFile, ohDestFile, true);
}), DispatcherPriority.ContextIdle);

因此我知道PDF的密码是ExamplePass。现在当我从我的程序中打开PDF时,我尝试了一些方法,只是;

if (selectedOHRecord.Path != string.Empty)
{
     Process.Start(selectedOHRecord.Path);
}

但可以理解,这只是打开Acrobat并要求输入密码。我也试过加入:

PdfDocument document = PdfReader.Open(selectedOHRecord.Path, "ExamplePass");

这取自PDFsharp网站本身,但是当我打电话时,根本没有任何事情发生。有没有办法打开PDF并为用户输入密码,这样他们就不必输入密码了?

2 个答案:

答案 0 :(得分:0)

如果PDF文件有用户密码,则Adobe Reader会提示输入密码。

您对PdfReader.Open的来电未将密码传递给Adobe Reader,因此会再次提示。

您可以设置所有者密码而不是用户密码。当Adobe Reader打开文件时没有提示,但会阻止编辑。

或者删除Unprotect示例中显示的密码,将没有密码的PDF文件保存到临时文件中,然后使用Adobe Reader打开。请注意,用户可以将文件从Adobe Reader保存到他们选择的文件夹中,以保留不受保护的副本 http://www.pdfsharp.net/wiki/UnprotectDocument-sample.ashx

答案 1 :(得分:-1)

需要澄清的一点:

PdfReader.Open();

正在调用 PdfSharp库

Process.Start();

正在呼叫 .Net库

让我们与后者呆在一起。如果要在默认的(由用户设置)PDF Reader中打开PDF,则只需调用Process.Start即可,方法如下:

Process.Start(selectedOHRecord.Path);

但是您必须定义是否要使用特殊程序(如Adobe Reader)打开它:

Process.Start("AcroRd32.exe", selectedOHRecord.Path);

特定于应用程序需要传递密码参数。遗憾的是,我没有在adobe documentation中找到 password 的参数。但是这是参数化请求的样子:

string parameterizedPath = $"{selectedOHRecord.Path} /A pass={securitySettings.UserPassword}";

或(我不确定顺序):

string parameterizedPath = $"/A pass={securitySettings.UserPassword} {selectedOHRecord.Path}";

然后:

Process.Start("AcroRd32.exe", parameterizedPath);

参数化的替代方法可以在这里找到:process.start() arguments。并且让我知道Adobe(或类似软件)是否确实有使用密码的方式,或者是否有我找不到的参数。