I am attempting to do the following:
- Retrieve a generated pdf from a web page
- Create an email message
- Attach the pdf to the message
- Send the message
I am able to retrieve the pdf from the web page and send the message with it as an attachment. However, when I try to open the attachment, I get the dreaded “Adobe Reader could not open ‘filename.pdf’ because it is either not a supported file type or because the file has been damaged” message.
The pdf is generated by an MVC3 page using a custom ActionResult to return the pdf. It looks like this
public class EnrollmentExpectationsPdfResult : FileResult
{
IList<AdminRepEnrollmentExpectationViewModel> adminreps;
public EnrollmentExpectationsPdfResult(IList<AdminRepEnrollmentExpectationViewModel> adminrep)
: this("application/pdf", adminrep)
{ }
public EnrollmentExpectationsPdfResult(string contentType, IList<AdminRepEnrollmentExpectationViewModel> adminrep)
: base(contentType)
{
adminreps = adminrep;
}
protected override void WriteFile(HttpResponseBase response)
{
var cd = new ContentDisposition
{
Inline = true,
FileName = "MyPDF.pdf"
};
response.AppendHeader("Content-Disposition", cd.ToString());
//Skip a bunch of boring font stuff
...
var writer = PdfWriter.GetInstance(doc, response.OutputStream);
writer.PageEvent = new EnrollmentExpectationPDFPageEvent();
doc.Open();
//Skip the doc writing stuff
...
doc.Close();
}
}
The controller method is here
public ActionResult EnrollmentExpectationsPDF()
{
//skip a bunch a database stuff
...
return new EnrollmentExpectationsPdfResult(adminList);
}
Here is the code at the heart of the problem…
//Get PDF
CredentialCache cc = new CredentialCache();
cc.Add(
new Uri("http://myserver/mypdfgeneratingpage"),
"NTLM",
new NetworkCredential("myusername", "mypassword"));
var webRequestObject = (HttpWebRequest)WebRequest.Create("http://iapps.national.edu/erp/Reports/EnrollmentExpectationsPDF");
webRequestObject.Credentials = cc;
var response = webRequestObject.GetResponse();
var webStream = response.GetResponseStream();
//Create Mail
System.Net.Mail.MailMessage eMail = ...
//Skipping to attachment stuff
ContentType ct = new ContentType()
{
MediaType = MediaTypeNames.Application.Pdf,
Name = "EnrollmentExpecations_2.pdf"
};
Attachment a = new Attachment(webStream, ct);
eMail.Attachments.Add(a);
//Send Message
....
As an experiment, I tried writing the downloaded file to disk
MemoryStream ms = new MemoryStream();
var fileStream = File.Create("C:\\MyPDF.pdf");
webStream.CopyTo(fileStream);
Viola, I am able to open the file from the diskwithout a problem.
What am I missing in order to make the attachment readable?
Just to make it clear to users, thanks to @rlb.usa
“Make sure you close and flush your stream after you send the object“