Create one pdf using iTextSharp C#, then download the same PDF. If tried to download the PDF getting blank page. What is wrong in my Code, assist me on this.
Here using PDF Writer created pdf file and added one paragraph then close the document. After that checking file exist or not. If file exists then read all the bytes and using ByteArrayContent download the file. But getting blanked file.
public HttpResponseMessage InvoicePdfDownload()
{
string file = Guid.NewGuid().ToString() + ".pdf";
string filePath = MyServer.MapPath("Assets/" + file);
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filePath, FileMode.Create));
document.Open();
document.Add(new Paragraph("Hello, World!"));
document.Close();
if (File.Exists(filePath))
{
byte[] bytes = File.ReadAllBytes(filePath);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(bytes);
result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(Path.GetFileName(filePath)));
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = Path.GetFileName(filePath) };
return result;
}
}
If we tried to open the file from saved filepath, able to see the content.
Why it's blank after downloaded?
You need to close the
PdfWriterHaving said that, it looks like you can avoid writing the PDF to a file in the first place, by using a
MemoryStream. You can also pass that stream all the way through toHttpResponseMessage.