2014-09-24 85 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

相關問題