In my Aspx page I have two buttons, btnGenerateReceipt is for generating receipt and btnAddNew for adding new receord. OnClick event of btnGenerateReceipt I am generating and opening a receipt as below.
protected void onGenerateReceipt(object sender, EventArgs e)
{
try
{
byte[] document = receiptByte;
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-word";
Response.AddHeader("content-disposition", "inline;filename=" + "Receipt" + ".doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(document);
//Response.Flush();
}
}
catch (Exception ex)
{
}
finally
{
//Response.End();
}
}
}
This opens Open/Save/Cancel dialog box, followings are my problems,
I need the word document to open automatically without the dialog box.
My second button's click function doesn't fire after I click btnGenerateReceipt button.
How can I generate&Open PDF file instead of word Doc?
Any idea?
The content sent by the server is handled by the web browser. You can not control from server side code whether the browser opens, saves or asks the user by default, as this is a browser setting.
EDIT
As for the second question about generating a PDF: There are many libraries out there to generate PDFs. However, if you already have the Word file ready, one solution would be to print the Word document to a PDF printer and send the resulting PDF.
Printing the document can be achieved using ShellExecute or the Process class with the verb print, then you could use a PDF printer like PDF-Creator or Bullzip to generate a PDF file.
This is what I'd try instead of "manually" generating the PDF file.
I need the word document to open automatically without the dialog box.
For the answer of the go with #Thorsten Dittmar answer.
My second button's click function doesn't fire after I click btnGenerateReceipt button.
Asp.net uses stateless connection, so do you think your written contents will remain in memory. i think it should not work as per my understanding. create response content and then write it to response and flush it.
How can I generate&Open PDF file instead of word Doc?
To generate pdf reference this. use iTextSharp like library to generate pdf then export/ save them as pdf.
Ref: ASP.NET 4: HttpResponse open in NEW Browser?
Response.AppendHeader("Content-Disposition", "inline; filename=foo.pdf");
You need to set the Content Type of the Response object and add the binary form of the pdf in the header. See this post for details:
Ref: Opening a PDF File from Asp.net page
private void ReadPdfFile()
{
string path = #"C:\Swift3D.pdf";
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length",buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
}
Ref Links:
ASP.NET 4: HttpResponse open in NEW Browser?
Generate pdf file after retrieving the information
ASP.NET MVC: How can I get the browser to open and display a PDF instead of displaying a download prompt?
Related
I am developing a KnoweldgeBase/Library in which a page lists PDF's and Word Documents associated with the topic selected. These files are uploaded into a folder the URL being "/Interface/AdminUploads/Miscellaneous/FILENAME".
I am listing the files via a table in which each row has an image of the file type, then the file title and then the date published (all created via another page). How can i have the PDF or Word documents opening when i click on the image for the document?
Try This Code.
string filepath ="/Interface/AdminUploads/Miscellaneous/FILENAME"; // Full Path of Pdf.
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(filepath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
Response.Flush();
Response.End();
You need to put the path in the url of the file.
You need to provide the full path you can ur Server.MapPath to get the full path.
Some useful links
How to open a file by clicking on HyperLink
Try the simple code
Response.Write(string.Format("<script>window.open('{0}','_blank');</script>", "pdflocation/" + "Example.pdf"));
I got it to work via...
System.Diagnostics.Process.Start(#fileLocation);
Running this code in a method on image click and passing in the variable 'fileLocation';
I have a page where I'm simply trying to write a pdf to the screen. Here's what I'm doing:
protected void ViewPDF(string url)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.TransmitFile(url);
Response.Flush();
Response.End();
}
This works in every browser and OS except for Firefox on Mac. Instead of displaying the pdf file in the browser, the browser opens the dialog to download the file, where you can Open it or Save it.
I've also tried this:
protected void ViewPDF(string url)
{
Response.Clear();
Response.ContentType = "application/pdf";
string path = Server.MapPath(url);
byte[] data = File.ReadAllBytes(path);
Response.BinaryWrite(data);
Response.End();
}
And I get the same result.
Anyone know how to fix this?
The browser needs to be able to render any given file format. Firefox (for Mac) does not include a PDF renderer out of the box. It's that simple.
See http://support.mozilla.org/en-US/kb/view-pdf-files-firefox-without-downloading-them.
You can try changing the content disposition header. There is a full discussion in this post:
Content-Disposition:What are the differences between “inline” and “attachment”?
I have some files in a folder on the harddrive, like C:\ExtraContent\ that has some PDF files. This folder is not part of the website. I was able to successfully upload a PDF to this folder using the default ASP.NET FileUploader, no problem.
What I would like to do is, create a hyperlink that links to a PDF in that folder C:\ExtraContent\somePDF.pdf
I am able to get close using a Button with the following code:
protected void Button1_Click(object sender, EventArgs e)
{
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData("C:\ExtraContent\somePDF.pdf");
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
The above works in terms of opening the file. But I can't get this to work with an ASP.NET HyperLink.
The reason I want to use a HyperLink is so that the user can choose to right-click and Save As, to download a copy. If HyperLink controls can only link to relative paths, what can I do to get my desired result?
Note: making the files I'm trying to access part of the site is not practical for us.
Basically allowing access to the folder the way you describe is a real security risk (because it requires hacking at the permissions), isn't trivial and in general should be avoided. The way that you achieve your desired behaviour is something along these lines.
Firstly create a blank aspx or ashx page.
Secondly, either in the Page_Load or ProcessRequest you want to use code along the following lines
string filePath = "c:\\Documents\\Stuff\\";
string fileName = "myPath.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(filePath + fileName);
context.Response.Clear();
context.Response.ContentType = "application/pdf";
context.Response.Cache.SetCacheability(HttpCacheability.Private);
context.Response.Expires = -1;
context.Response.Buffer = true;
context.Response.AddHeader("Content-Disposition", string.Format("{0};FileName=\"{1}\"", "attachment", fileName));
context.Response.BinaryWrite(bytes);
context.Response.End();
I haven't tested this and taken it from my head so it might need some tweeks but the above code should get you on the right track to cause the persons browser to begin downloading the file you provide.
EDIT: I just realized (after rereading your question) your problem was slightly different to what I thought, to get your issue resolved simply make the hyperlink button you are using link to a page that can process the request as described above. IE: An ashx or aspx page
You need to create a hyperlink to a page that acts as a 'proxy' so that the page will return a response that contains the file stream.
You cannot create a link to a file that is not prt of your site.
I looking for the easiest way to export the currently viewed asp.net web page to a PDF document using iTextSharp - it can be either a screenshot of it or passing in the url to generate the document. Sample code would be greatly appreciated. Many thanks in advance!
On a past project, we used Supergoo ABCPDF
to do something like you need to and it worked quite well. You basicly feed it an url and it process the HTML page into a PDF.
On the downside, it's a licensed software with costs associated to it and we had some performance issues when exporting a lot of large PDF at the same time.
Hope this helps !
Adding to what Darin said in his comment.
You can try using wkhtmltopdf to generate PDF files. It takes URL as input. This is what I have used for my SO application so2pdf.
It is not that easy (or i think so), i had same problem and i had to write code to generate exact page in pdf. It depends of page and used styles etc. So i create drawing of each element.
For some project i used Winnovative HTML to PDF converter but it is not free.
Give a try with PDFSharp (to generate PDF files at runtime), and it's Open Source library :
http://pdfsharp.com/PDFsharp/index.php?option=com_content&task=view&id=27&Itemid=1
Alternative solution : http://www.bratched.com/en/component/content/article/76-how-to-convert-xhtml-to-pdf-in-c.html
There is an example Convert the Current HTML Page to PDF on WInnovative website which does exactly this. The relevant C# code to convert the currently viewed asp.net web page to a PDF document is:
// Controls if the current HTML page will be rendered to PDF or as a normal page
bool convertToPdf = false;
protected void convertToPdfButton_Click(object sender, EventArgs e)
{
// The current ASP.NET page will be rendered to PDF when its Render method will be called by framework
convertToPdf = true;
}
protected override void Render(HtmlTextWriter writer)
{
if (convertToPdf)
{
// Get the current page HTML string by rendering into a TextWriter object
TextWriter outTextWriter = new StringWriter();
HtmlTextWriter outHtmlTextWriter = new HtmlTextWriter(outTextWriter);
base.Render(outHtmlTextWriter);
// Obtain the current page HTML string
string currentPageHtmlString = outTextWriter.ToString();
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
// Set license key received after purchase to use the converter in licensed mode
// Leave it not set to use the converter in demo mode
htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";
// Use the current page URL as base URL
string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;
// Convert the current page HTML string a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(currentPageHtmlString, baseUrl);
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Convert_Current_Page.pdf; size={0}", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
}
else
{
base.Render(writer);
}
}
I have some data in the form of a string. I want to write this data to a file and save the file to the specified path. The path would be specified by opening a save as dialog on the button click. How can this be achieved??
The file is saved into the server initially with this code
string getnote = txtdisplay.Text.Trim();
String filepath = Server.MapPath(#"img\new1.txt");
System.IO.FileStream ab = new System.IO.FileStream(filepath, System.IO.FileMode.Create);
System.IO.StreamWriter Write101 = new System.IO.StreamWriter(ab);
Write101.WriteLine(getnote);
Write101.Close();
Response.ClearContent();
From the server get the file as attachment.Use the following code for save as dialog box for downloading or saving the file. The file will save by default in the download folder. To save to the specified location change the browser settings.
Response.ContentType = "text";
Response.AppendHeader("Content-Disposition", "attachment; filename=new1.txt");
Response.TransmitFile(Server.MapPath("~/img/new1.txt"));
Response.End();
Response.ContentType = "application/octet-stream" (or content type of your file).
Response.AppendHeader("content-disposition", "attachment;filename=" & strFileName)
There is no Save As dialog in ASP.NET.
Remember, your ASP.NET application is running in a browser on a user's computer. You have no access to the user's file system, including the Save As dialog.
However, if you send the user a file, as an attachment, most browsers will display a dialog asking the user whether to save the file or open it. Maybe the user will choose to save it. That's what the example from phoenix does.
You could use a LinkButton (or regular link) and have the url point to a handler (ASHX) that retrieves the data and sends back a response with content disposition set to attachment. Write the data to the response. You'll also need to set up some other headers in the response -- such as content type and length. This would give the document (file) a regular link that could perhaps be bookmarked (if a regular link) in the future so that it can be retrieved again. You'd need to pass enough data in the query string to be able to identify which data is to be downloaded.
if I userstand you correctly, here -
saveFileDialog1.DefaultExt = "*.file";
saveFileDialog1.Filter = "File|*.file|Other File|*.OFile|";
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFileDialog1.FileName.Length > 0)
{
WebClient wc = new WebClient();
wc.DownloadFile("http://www.exaple.com/exaplefile", saveFileDialog1.FileName);;
}