I am currently using ITextSharp to create a PDF using a .Net 3.5 ASPX page. Everything works well.. the only issue is that in chrome(Version 42.0.2311.135) when I click the save button or right click and say save as it tries to save as an .aspx page. I don't experience these issues when using Firefox or Internet Explorer. I tried disabling the chrome PDF viewer and it just automatically saves the file as an aspx file. I've included my code below which is fired from a button click. I am assuming it is the way I am handling the response? Any ideas?
iTextSharp.text.Document d = new iTextSharp.text.Document(PageSize.A4, 20, 20, 20, 20);
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
w = PdfWriter.GetInstance(d, stream);
//add stuff to itext document
d.Close();
byte[] b = stream.ToArray();
stream.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.BinaryWrite(b);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
UPDATE:
Wanted to share my findings in case it saves someone the headache. Adding Response.AddHeader("Content-Disposition", "inline;filename=myfilename.pdf"); fixed most of the issues but I was still experiencing a problem with the save button in the Google chrome viewer(print worked fine but save prompted the user to save the page and not the pdf). The PDF is being generated on a .aspx page through a button click. After it is generated I clear the response and dump the PDF to the page. The form element on the page didn't have a method set so it was being sent as post(found this out through fiddler). This page was being shared through an iframe. I changed the method to GET on the page and everything is now working as expected.
Try with:
Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.pdf");
Related
I an trying to open word document on hyperlink click. Now below code is opening dialogbox ans asking for saving.
How to open directly word document without user asking dialogbox for saving or open? just need to popup with word doc.
Response.Clear()
Response.ContentType = "application\msword"
Dim file As New System.IO.FileInfo(Server.MapPath("/UserManual\Carangi Reunderwriting Website User Manual.docx"))
Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name)
Response.AddHeader("Content-Length", file.Length.ToString())
Response.TransmitFile(file.FullName)
Response.Flush()
Response.End()
Browser settings can override the content-disposition header. You might want to check and see if your document opens inline in another browser or on another machine. Seems to me that conservative default settings these days should show a save dialog before opening a word document from a web page.
In an ASP.NET 2.0 application, using Google Chrome 13 on Windows.
My app dynamically generates a PDF report when the user browses to a particular aspx page. For the most part, things work fine on various browsers.
However, on Chrome, when Chrome's PDF viewer is being used, the following can happen :
- the user presses the floating diskette icon on the bottom right hand side of the viewer to save the PDF document. The file is saved with the aspx page's name. e.g. Report.aspx .
If I open that downloaded aspx file in Adobe Reader, it opens up ok as a PDF document. But is there a way to get chrome to default the name of the file to save to have a ".PDF" extension ?
EDIT :
The code for the report generation page looks something like this :
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "application/pdf";
byte[] data = GenerateReportHere(); // dynamically generate PDF report
Response.AddHeader("Content-Length", data.Length.ToString());
Response.BinaryWrite(data);
Response.Flush();
Response.End();
}
Note that I don't want to use a "Content-Disposition" header like :
Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
because that causes the browser to ask the user if they want to download the file. In Chrome it won't display it in its PDF viewer - just gives the user the chance after downloading to open the file using whatever program they have associated with the ".pdf" file extension.
You should try using content-disposition header while streaming the PDF file to the browser. For example,
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=[ReportName].pdf");
// Code to stream pdf file content to the client
...
For more info about content disposition, see
http://www.jtricks.com/bits/content_disposition.html
http://greenbytes.de/tech/webdav/draft-reschke-rfc2183-in-http-latest.html
Since chrome is up to date with HTML5, we can use the shiny new download attribute!
Works
My problem looks like this.
I have a grid with documents (Id's). Now when somebody clicks at a row I would like to allow him to download or show that document. But to make it esier let's say that I would do this on a button click. I tried two approaches but none of them worked form me.
I tried to response.binarywrite on the button click:
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "application/postscript mime";
Response.AddHeader("content-disposition", "attachment; filename=test.ps");
Response.AddHeader("content-length", _excuteGetDocumentResult.Length.ToString());
Response.ContentEncoding = new System.Text.UTF8Encoding();
Response.BinaryWrite(_excuteGetDocumentResult);
But nothing happens and when I try to modify this code I usually get some javascript errors saying sommething about changing the response...
The socond approach was opening new window and on page load adding the code above.
<asp:Button Text="ShowResult" OnClientClick="radopen('ShowResult.aspx','ShowDocumentDialog'); return false;"
runat="server" />
The socond approach works but my opened window still exists after saving or canceling the explorer saving file dialog window. I tried to add some javascript to close it but it only works where there is no response.binarywrite on the load page...
Any ideas how I can achive what I want?
In method 1.
try Response.End(); after Response.BinaryWrite(_excuteGetDocumentResult);
EDIT 2
It appears that moving the object tag in the Dom is the cause of the problem. I added an iframe directly to the page and it works fine without any problems.
However, when I move that iFrame into a modal dialogue box (http://www.ericmmartin.com/projects/simplemodal/) the PDF disappears (the object tag no longer renders correctly).
So it appears that it's no longer a question about my handler, but more a question about why moving the "object" (or embed) tag in the DOM (which lives inside an iFrame) causes it to "blank-out."
Also, when the pdf is moved from the modal dialogue back to its original position, it appears correctly. So, perhaps I should focus more on the modal dialogue itself.
Thoughts? Thanks for your suggestions thus far.
EDIT 1
So I've made some modifications for testing.
I've got the iframe to output an object tag for pdf requests along with the server time.
Response.AddHeader("content-type", "text/html");
WebClient client = new WebClient();
Response.Write("<html><head></head><body><h1>"+ DateTime.Now.ToString() + "</h1><object height='100%' width='100%' name='plugin' data='" + Request.Url.ToString() + "&embed=true' type='application/pdf' /></body></html>");
Response.Flush();
Response.Close();
Response.End();
Now I get a page with the current time correctly, but the object only displays the PDF the first time after I publish the aspx page. So it appears to be some sort of caching issue? Except that the object isn't loading anything (not even the previously loaded PDF).
If right click on the iframe and refresh the page, the object loads up fine. (The same is true if I use an embed tag).
Original Question
I know there are a lot of questions on this...
streaming PDF data through an ASPX page
Server generated PDF not displaying in IFrame on aspx page on some (but not all )PCs
Displaying a PDF Document in ASP.net page
But they either weren't answered, or the answer didn't work.
Environment
.Net 4
Adobe 9.3.4
IIS 5.1
XP sp3
VS 2010
IE 8.0.6001.18702
Background
The pdf's I'm streaming come from a storage repository where the files don't have any extensions (this is done for security). I look up the file in the database and stream it back to the client via the following code:
Response.Clear();
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(sPath);
Response.AddHeader("content-length", buffer.Length.ToString());
Response.AddHeader("content-disposition", "inline;filename=" + fileName);
Response.AddHeader("expires", "0");
Response.AddHeader("Content-Type", "application/pdf"); //this is usually dynamic to support other types (doc, xls, txt, etc.)
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.Flush();
Response.Close();
Response.End();
This works for every file type (doc, txt, xls, html) when used directly in the browser or in the iframe (displayed as a modal popup) with the exception of pdf files. They do not work reliably when accessed via the iframe, but work fine when accessed directly in the browser.
The only time it does work is the first time I request a document after I publish the aspx page that is serving these files. All subsequent hits return a blank page (even from new tabs or browser windows). Firefox reliably displays the pdf every time regardless.
Attempted Solutions
I've tried various ways I of streaming the file:
Response.TransmitFile(sPath);
Response.WriteFile(sPath);
//As well as some others
I've tried adding .pdf to a parameter at the end of the request
http://www.myurl.aspx?File=test.pdf
I've tried making the URL unique by adding a time stamp
http://www.myurl.aspx?File=test.pdf&Unique=Friday__September_17__2010_12_02_16_PM
Un-Attempted
I've read about IIS compression causing problems, but it was for a newer version of IIS.
Didn't try using embed tag since I would like to stick to the iFrame if possible (The existing infrastructure uses it).
Any help would be greatly appreciated!!!
Thanks.
I had a similar problem that arose when the PDFs were streaming over SSL (IE only, FF didn't exhibit the issue) that was only solved by doing the following:
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.AppendHeader("Content-Disposition", "inline; attachment; filename=Filename.pdf");
Response.ContentType = "application/pdf";
Response.WriteFile(path);
Response.Flush();
Response.End();
So I gave up and decided to use a standard IE popup window instead.
window.open(URL, 'Window', 'height=' + pageHeight + ',width=' + pageWidth + ',top=0,left=0,resizable');
I had to render the pdfs in an object tag and everything else inside an iframe within the popup for it to work, but it works...
if (sDocType == "pdf")
{
Response.AddHeader("content-type", "text/html");
WebClient client = new WebClient();
Response.Write("<html style='margin:0px;padding:0px;'><head></head><body style='margin:0px;padding:0px;'><object height='100%' width='100%' name='plugin' data='" + Request.Url.ToString() + "&embed=true' type='" + zGetContentType(HttpContext.Current.Request.QueryString["docType"]) + "'><param name='src' value='" + Request.Url.ToString() + "&embed=true' />alt : <a href='" + Request.Url.ToString() + "&embed=true'>View</a></object></body></html>");
Response.Flush();
Response.Close();
Response.End();
}
else
{
Response.AddHeader("content-type", "text/html");
WebClient client = new WebClient();
Response.Write("<html style='margin:0px;padding:0px;'><head></head><body style='margin:0px;padding:0px;'><iframe frameborder='0' scrolling='no' height='100%' width='100%' src='" + Request.Url.ToString() + "&embed=true' /></body></html>");
Response.Flush();
Response.Close();
Response.End();
}
I'm not sure that you need to set the filename, especially if it doesn't have the .pdf extension. When streaming PDFs to browser in the past, I've always used this code:
Response.Clear();
Response.ContentType = "application/pdf";
Response.BinaryWrite(pdfBuffer);
Response.Flush();
Otherwise, there's a possibility that something has hosed over the registry settings for the application/pdf CLSID on the client computer.
I was able to solve a similar problem (pdf inside of modal window internet explorer)
by taking out the iframe. Instead, load the pdf into an html object element.
see the link below:
http://intranation.com/test-cases/object-vs-iframe/
To sum it up:
The setup that did not work:
jQuery floatbox, loads html fragment with iframe, load aspx page into iframe, load pdf into aspx page
The setup that now works:
jQuery floatbox, loads html fragment, append object element.
before appending the object element, set data
attribute of object element to the aspx page url
I have this lead generation form and after they give us their information, I would like the form's thank you page to popup a window where the user can save the file or open it.
This web page will be served from a Microsoft server so .net C# or javascript are options.
thx
I Assume, your problem is to display a thank you page, and also to open a new save / run dialog.
The below js code, / HTML code in the thank you page will render the thank you page, and make the browser request for the file mentioned in the URL. If that is configured properly as mentioned by others, it will prompt the dialog
Try
Javascript
document.write("<META HTTP-EQUIV=\"refresh\" content=\".1; URL=http://domain.come/my.exe\">");
HTML
<META HTTP-EQUIV="refresh" content=".1; URL=http://domain.come/my.exe">
Good luck getting any browser to open an .exe file... Warning Will Robinson... Warning...
Anyways, here's a snippet....
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadName);
while (dataToRead > 0)
{
if (Response.IsClientConnected)
{
fileLength = iStream.Read(buffer, 0, buffer.Length);
Response.OutputStream.Write(buffer, 0, fileLength);
Response.Flush();
dataToRead = dataToRead - fileLength;
}
else
{
dataToRead = -1;//prevent infinite loop if user disconnects
}
}
Edit: Ok, i suppose you could create the thank you page with a hidden button on it, inject some javascript to click that button upon load, which would then execute the code to dump the file into the response stream.
I would imagine your answer could be find in one of these previous questions
https://stackoverflow.com/search?q=force+download
You cannot launch a file on the users machine unless you have some ActiveX control or Java applet with permissions to do so installed.
You can create the file on your server and send it to the browser. The user will be prompted to save or open the file.