Reputation: 237
I have crystal report. I want to export it to PDF. At the same time I want to Encrypt it using 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?
Upvotes: 0
Views: 2063
Reputation: 5878
Try exporting to stream, then encrypting the memory stream, rather than working with the exported file. I use PdfSharp and here's my workflow.
// 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?
}
}
Upvotes: 3