简体   繁体   English

使用itextSharp在Crystal Report导出过程中加密PDF

[英]Encrypt PDF during Crystal Report Exporting using itextSharp

I have crystal report. 我有水晶报告。 I want to export it to PDF. 我想将其导出为PDF。 At the same time I want to Encrypt it using iTextSharp. 同时,我想使用iTextSharp对其进行加密。

This is my code: 这是我的代码:

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);
}

I am getting following 我正在关注

Error: "The process cannot access the file because it is being used by another process" 错误:“该进程无法访问该文件,因为该文件正在被另一个进程使用”

What is the problem? 问题是什么? Is there any other way to do this? 还有其他方法吗?

Try exporting to stream, then encrypting the memory stream, rather than working with the exported file. 尝试导出到流,然后加密内存流,而不是处理导出的文件。 I use PdfSharp and here's my workflow. 我使用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);

EDIT 编辑

// 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?
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM