Displaying PDF from Memory Stream to browser - asp.net

I am trying to display a pdf created dynamically and display it in the browser, but I am getting the below characters( a whole lot of them)
Im using iTextSharp
\�(l�x�)�(�)���g���29��2�`C�B�Wa���[�(�o��x��3�J :k��v�os�R
The code which I used to create the pdf does work when sending it by email as an attachment.
Maybe im wrong on displaying it ?
....
doc.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=labtest.pdf");
Response.Buffer = true;
stream2.WriteTo(Response.OutputStream);
Response.End();
code above is in a controller method

Answered in comments of question.
Credit to Chris Haas
AJAX in its general form is text-based which is why you are seeing a
text-representation of a PDF. You need to switch to binary processing
if you want to work with binary data but that's a whole different
question. See this for an intro html5rocks.com/en/tutorials/file/xhr2

Related

ASP.NET - PDF downloading in .aspx format instead of PDF

I created a PDFViewer form in ASP.NET, and it works fine within the app. In the last part of the code, I use these lines to generate the PDF file from information I used previously (I'm using the PDFSharp library):
MemoryStream stream = new MemoryStream();
pdf.Save(stream, false);
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("content-length", stream.Length.ToString());
response.BinaryWrite(stream.ToArray());
response.Flush();
stream.Close();
response.End();
The file looks good, I see all the PDF browser options to print, zoom, downlad, etc.
The issue I'm having is, when I click on the download button, it wants to download the PDF as "PDFname.aspx", instead of "PDFname.pdf", although I am specifying the content type is "application/pdf". Which other thing could be missing?

PDF file sometime being displayed as garbage

I am having a user who is reporting that files are being displayed as raw data in his browser. He uses Internet Explorer.
The files are being served via a .ashx handler file and it has been working until.
This is the relevant part of my .ashx handler:
context.Response.Clear()
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name)
context.Response.AppendHeader("Content-Length", size.ToString)
context.Response.ContentType = "application/pdf"
context.Response.TransmitFile(fullname)
context.Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
Can anyone figure something out of this screenshot?
Update: this behaviour appears on Windows 10 when running either IE 11 or Edge and only the second time a file is being opened. It happens for both .pdf and .docx files.
This is the code I use to stream PDFs to a client. It works in IE 11. The main difference is that I am using BinaryWrite which based on your code, you may not want to do..
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName + ".pdf");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.End();
There might be a solution here
I'll like this as well just in case..
According to this thread, it could be as simple as replacing Response.Close with Response.End (or in your case.. adding)
I finally found the answer myself - it had to do with the HTTP header content-length which i mistakenly submitted with a value exactly 1byte too large.
This caused the strange behavior in only IE/Edge and only Windows 10 as described in the OP.
I had the same problem with an aspx page that transmits file to browser in Page_Load event handler.
My mistake was an absense of
Response.End();
method call. When I added this line the problem has gone.

PDF from content of asp.net page

I'm trying to create a pdf of the content on a page ("returnsPage.aspx?id="returnId) and allow the user to download this directly when clicking the button.
However in my onClick method I have the following code:
lnkLoadPDF.CommandArgument = "/returns/returnsPage.aspx?id="+returnId.ToString();
string virtualPath = lnkLoadPDF.CommandArgument;
string fileName = System.IO.Path.GetFileName(virtualPath);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.WriteFile(virtualPath);
Response.ContentType = "";
Response.End();
Response.Redirect("/returns/returnsPage.aspx?id="+returnId);
which returns this error:
'/returns/returnsPage.aspx?id=23' is not a valid virtual path.
Can anyone please tell me what I'm doing wrong?
Thanks!
In order to turn a webpage into a pdf, you must convert it to pdf on the server. In order to do that, you must have a program on the server that can do that for you.
I've tried a variety of webpage-to-pdf converters and one of the better ones is a free, open source program called wkhtmltopdf.
After you create the pdf, you can either redirect the user to the newly created pdf (discouraged), or prompt them to download it with a savefile dialog.
If you get stuck, just search for wkhtmltopdf on stackoverflow or post another question.
You can't send a file to the client and redirect him to a new location during the same request. You also can't create a PDF from a webpage without some kind of component that converts the HTML into a PDF, it's (quite a bit) more tricky that what I think you're trying to attempt.
As for your exception, are you sure returnsPage.aspx exists? :)

asp.net - exporting table

I have a big problem with exporting my table to Excel file format.
Firstly I created code which runs on server and allows me to export data to Excel. Due to the fact that my table is created dynamically from the database there is nothing WITHIN the table at that stage, so no data were exported.
My second approach was targeting the final compiled table on the client side using either javascript or a very nice jQuery plugin called "DataTables" (www.datatables.net). Both of the attempts failed. Javascript seems to be to complex for me, plus it has difficulties running in Firefox, plugin on the other hand requires a very specific table structure which I am afraid I cannot provide.
So, a new idea of mine is: grab the page just after compiling and building it on the server, but before sending it to the browser. Target THE table and source its data using function on server. Finally export data to Excel, and send the page to the browser. Now. Is it possible? And if yes, then how?
I am beginner in programming world so any constructive suggestions and criticism would be highly appreciated. I would not mind any hard code examples ;)
You can try doing something like this:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
//if you're exporting a table put the table in a placeholder and render
//the placeholder to the text writer here
grdJobs.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
What you need to do is export your query results in a .CSV file. CSV files can be opened in Excel no problem at all. http://wiki.asp.net/page.aspx/401/export-to-csv-file/ This shows you how to export into a .CSV format.
You're going to get a lot of suggestions instead of answers on this here. My recommendation would be to try the jQuery plugin: table2csv in order to create a more universal file format. But there are ways to target an actual Excel format, like this project.
If you want to export to actual XLS or XLSX instead of just CSV or something that just "opens" in Excel, there are third party tools that can help you with this. One example here:
http://www.officewriter.com

How do I send a binary blob to a client browser?

Pardon the dumb newbie question here; web programming isn't my forte... (blush)
I have an aspx page running on a web server. I have a blob (byte array) containing any kind of binary file, plus a file name.
I would like to push this file to be downloaded through the browser onto the client, and opened using whatever application is default for this file type. I really don't want to save the blob as a file on the server; that will leave a terrible housekeeping mess that I just don't want to think about.
I did try googling this question, but I guess I'm using the wrong keywords.
This really should be obvious how to do it, but I'm having no joy.
What is the trick?
Thanks!
Response.BinaryWrite(byteArray);
You should also set the content type
Response.ContentType = "application/pdf";
But that will be based on your file type.
And the file name (and everything together) is done like this
Response.AddHeader("content-disposition",
String.Format("attachment;filename={0}", fileName));
Response.ContentType = "application/pdf";
Response.BinaryWrite(byteArray);
First, you have to know the mime type. Once you know that, you can set the Response.ContentType property. After that, just use Response.BinaryWrite(). If you don't first set the ContentType property, the client will have almost no chance of opening the file correctly.

Resources