Reputation: 3864
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,
Any idea?
Upvotes: 0
Views: 4555
Reputation: 56727
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.
Upvotes: 4
Reputation: 18290
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?
Upvotes: 1