How to open save dialog box for saving pdf - c#

I truly appreciate your suggestions. I am using MVC3 and I want user to save to his own path by opening a dialog with password protected. Can you guys please help me on this.
Below is my code:
mydoc.GenerateLetter(PdfData);
string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (MemoryStream m = new MemoryStream())
{
m.Write(mydoc.DocumentBytes, 0, mydoc.DocumentBytes.Length);
m.Seek(0, SeekOrigin.Begin);
string OutputFile = Path.Combine(WorkingFolder, PdfData.Name + ".pdf");
using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(m);
PdfEncryptor.Encrypt(reader, output, true, "abc123", "secret", PdfWriter.ALLOW_SCREENREADERS);
}
}

If you want to show a Save As dialog so that the user can choose the location to save the PDF file on his computer you could use the Content-Disposition HTTP header and set it to attachment. Also in an ASP.NET MVC application instead of saving the file to the server (which is what your code currently does), you should stream it to the client:
public ActionResult DownloadPdf()
{
var mydoc = ...
mydoc.GenerateLetter(PdfData);
byte[] pdf = mydoc.DocumentBytes;
var reader = new PdfReader(pdf);
using (var encrypted = new MemoryStream())
{
PdfEncryptor.Encrypt(reader, encrypted, true, "abc123", "secret", PdfWriter.ALLOW_SCREENREADERS);
return File(encrypted.ToArray(), "application/pdf", PdfData.Name + ".pdf");
}
}
Now when a user navigates to this controller action /SomeController/DownloadPdf he will be presented with a Save As dialog allowing him to download the encrypted PDF file and store it in a chosen location on his computer.

Related

Xlsio Excel file as Mailkit attachement

I'm using Mailkit to send email, and I would like to send a created Excel file (thanks to Xlsio) as an Email attachement.
I achieved to send the email, I see the attachement with good extension (.xlsx) but when I want to open it I have an error "Format or extention is not valid".
This is what I've coded for creating the Excel file
FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
workbook.SaveAs(stream, ExcelSaveType.SaveAsXLS);
FileAttachementDto file = new()
{
FileName = fileName,
File = stream, // Type of File property is Stream
};
What I'v coded for adding the file to the email attachements
var attachements = MimeEntity.Load(
new ContentType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
new MemoryStream(myFile.File.ReadAsBytes()));
bodyBuilder.Attachments.Add(attachements);
Thanks
Don't do this:
var attachements = MimeEntity.Load(
new ContentType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
new MemoryStream(myFile.File.ReadAsBytes()));
That is for parsing HTTP web responses.
Just do this instead:
var attachment = new MimePart ("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
FileName = "fileName.xls",
ContentTransferEncoding = ContentEncoding.Base64,
Content = new MimeContent (new MemoryStream (myFile.File.ReadAsBytes ()))
};
We suggest you to set the workbook version as Xlsx before saving the Excel document and remove the ExcelSaveType.SaveAsXLS parameter in SaveAs method of IWorkbook.
Code Snippet:
FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
workbook.Version = ExcelVersion.Xlsx;
workbook.SaveAs(stream);
FileAttachementDto file = new()
{
FileName = fileName,
File = stream, // Type of File property is Stream
};
​​​

Saving pdf stream in a file as a pdf

I have a variable which holds a pdf stream , this variable is of type System.Threading.Tasks.Task<Stream>. I want to save this pdf stream in a pdf file but I am not sure how to do so . Below is a piece of code I tried to work on . Any ideas as to what I can try to save this stream in a file
System.Threading.Tasks.Task<Stream> pdf = //Some logic here which gets a pdf stream
I want to store the pdf content in the variable in a file as a pdf
For that I worote the method
public static void SaveStreamAsFile(string filePath, System.Threading.Tasks.Task<Stream> inputStream, string fileName)
{
string path = Path.Combine(filePath, fileName);
using (FileStream outputFileStream = new FileStream(path, FileMode.Create))
{
// logic
}
}
Read the input stream and write it to the output stream..
public static async Task SaveStreamAsFile(string filePath, System.Threading.Tasks.Task<Stream> inputStream, string fileName)
{
var stream = await inputStream;
var path = Path.Combine(filePath, fileName);
var bytesInStream = new byte[stream.Length];
await stream.ReadAsync(bytesInStream, 0, (int) bytesInStream.Length);
using (var outputFileStream = new FileStream(path, FileMode.Create))
{
await outputFileStream.WriteAsync(bytesInStream, 0, bytesInStream.Length);
}
}

Missing Email Header after export to mht or eml with Exchange Web Services

i'm trying to export a email as mht or eml.
The export is working but the content is incomplete.
The Export only contains the content of the green box.
The Content from the red box is missing (sender, recipient, subject, sent).
string emlFileName = #"C:\export\email.eml";
string mhtFileName = #"C:\export\email.mht";
// Save as .eml.
using (FileStream fs = new FileStream(emlFileName, FileMode.Create, FileAccess.Write))
{
fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length);
}
// Save as .mht.
using (FileStream fs = new FileStream(mhtFileName, FileMode.Create, FileAccess.Write))
{
fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length);
}

Check FileName From HttpHostedFileBase is File Name or File Path

I am developing an application which store filename in database. For Mozilla & Chrome it is showing FileName only but in IE it is showing full path of file. Now I want to check whether given filename is filename or filepath. Is there any way to do it?
Here is my code:
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
byte[] image = null;
var file = attachments.First();
// Some browsers send file names with full path. We only care about the file name.
string filePath = Server.MapPath(General.FaxFolder + "/" + file.FileName);
file.SaveAs(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using (BinaryReader br = new BinaryReader(fs))
{
image = br.ReadBytes((int)fs.Length);
}
TempData["Image"] = image;
System.IO.File.Delete(filePath);
return Json(new { status = "OK", imageString = Convert.ToBase64String(image) }, "text/plain");
}
Well,If you go with getting filename only in any browser then you should write
Path.GetFileName(e.fileName);
It will return filename only in any browser
Thanks
Instead of check whether the file has a path or not, what you can do is to just use
GetFileName(path);method

save attachment file in microsoft dynamic crm to computer

CRM saves attachements in AnnotationBase base table.
How can I convert the text in the DocumentBody entity back to file and save it the file system?
I have got the value of the documentbody field and then try to write it in my computer but my is file corrupted.
I am using this code:
String DocumentBody = Convert.ToBase64String(
newUnicodeEncoding().GetBytes("UEsDBBQABgAIAAAAIQDQf9XuxAEAAE4HAAATAAgCW0NvbnRlbnRfVHlwZXNd Lnh/abtPgp4eu7+W68C2dvLaWtho32sTajdkFmweGeKMQYTD5MrcDFf"));
using (FileStream fs = new FileStream("c:\\1.docx", FileMode.Create, FileAccess.Write))
{
byte[] bytes = Convert.FromBase64String(DocumentBody);
fs.Write(bytes, 0, bytes.Length);
}
The string in GetBytes is the same as documentbody field in annotationBase table.
Here is the code that has always worked for me - and I can confirm this has worked for me using data retreived from CRM 4 with the CRM 4 SDK. I did a project almost exactly the same about 18 months ago where we had to archive off all the notes and e-mails from CRM.
If you are still having issues see the original source of this code
public static void ExportFile(string fileName, string content)
{
byte[] fileContent = Convert.FromBase64String(content);
using (FileStream file = new FileStream(fileName, FileMode.Create))
{
using (BinaryWriter writer = new BinaryWriter(file))
{
writer.Write(fileContent,0,fileContent.Length);
writer.Close();
}
file.Close();
}
}

Categories