使用itextSharp在Crystal Report导出期间加密PDF

时间:2014-09-24 12:11:41

标签: c# crystal-reports itextsharp

我有水晶报告。我想将其导出为PDF。同时我想使用iTextSharp加密它。

这是我的代码:

SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "PDF File|*.pdf";

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    string filepath = saveFileDialog1.FileName;
    crd.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, filepath);
    var doc = new Document(PageSize.A4);
    PdfReader reader = new PdfReader(filepath);
    PdfEncryptor.Encrypt(reader, new FileStream(filepath, FileMode.Open), PdfWriter.STRENGTH128BITS, "pass", "pass", PdfWriter.AllowScreenReaders);
}

我正在关注

  

错误:   "进程无法访问该文件,因为它正被另一个进程使用"

有什么问题?还有其他办法吗?

1 个答案:

答案 0 :(得分:2)

尝试导出流,然后加密内存流,而不是使用导出的文件。我使用PdfSharp,这是我的工作流程。

// create memory stream
var ms = report.ExportToStream(ExportFormatType.PortableDocFormat)
// Then open stream
PdfDocument doc = PdfReader.Open(ms);
// add password
var security = doc.SecuritySettings;
security.UserPassword = password;
ms = new MemoryStream();
doc.Save(ms, false);

修改

// I don't know anything about ITextSharp
// I've modified your code to not create the file until after encryption
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    string filepath = saveFileDialog1.FileName; // Store the file name
    // Export to Stream
    var ms = crd.ExportToStream(ExportFormatType.PortableDocFormat);
    var doc = new Document(PageSize.A4);
    ms.Position = 0; // 0 the stream
    // Create a new file stream
    using (var fs = new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        PdfReader reader = new PdfReader(ms); // Load pdf stream created earlier
        // Encrypt pdf to file stream
        PdfEncryptor.Encrypt(reader, fs, PdfWriter.STRENGTH128BITS, "pass", "pass", PdfWriter.AllowScreenReaders);
        // job done?
    }
}