2014-09-24 179 views
0

我有水晶报告。我想将其导出为PDF。同时我想用iTextSharp对它进行加密。使用itextSharp在Crystal Report导出期间加密PDF

这是我的代码:

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

我得到以下

Error: "The process cannot access the file because it is being used by another process"

问题是什么?有没有其他方法可以做到这一点?

+0

您的实际问题是,你正在努力,而你是从文件中读取到写入文件。一般来说,这两项行动不应该同时进行。 @reckface解决方案可能是最好的选择。 – 2014-09-24 13:39:42

回答

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? 
    } 
} 
+0

您能否使用itextSharp dll – 2014-09-24 13:18:10

+0

编写此代码否其显示以下错误:在itextsharp.dll中发生未处理的“iTextSharp.text.exceptions.InvalidPdfException”异常 附加信息:未找到PDF标头签名。 – 2014-09-24 13:56:23

+0

啊,我明白了。对不起,应该是ExportFormatType.PortableDocFormat – reckface 2014-09-24 14:03:23

相关问题