Title may not describing well what I'm asking for,
Actually I'm looking for some guidelines to solve my code issue,
I'm creating a application that will export the HTML page with data in
Grid view and logo images to excel. What I've done so far in below:
private void ExportExcel()
{
//This method is defined in ButtonClick Event
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
GridView2.AllowPaging = false;
string FileName = "Exported" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
this.EnableViewState = false;
GridView2.DataBind();
Response.Write(ExportDiv.InnerHtml);
GridView2.GridLines = System.Web.UI.WebControls.GridLines.Both;
GridView2.HeaderStyle.Font.Bold = true;
GridView2.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}
This above code is working fine, but they issue is with the logo image Attach images shows issue with logo image,
Check Image here
The logo image is not set inside a cell what i actually need. What i
need is shown in this pic Please check image
Without using any outsource library you can do this, Things that was causing issue the alignment of the Grid view and HTML code.
So what I've done is create a div and named it ExportDiv and add
HTML Table inside ExportDiv, after that I write my HTML code inside
table by adding row and columns again and again, and add grid view
inside my Table which was created inside ExportDiv.
Following is the code that works behind the click event.
private void ExportToExcel(string strFileName)
{
StringBuilder sb = new StringBuilder();
string attachment = "attachment; filename=" + strFileName;
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
StringWriter oStringWriter = new StringWriter();
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
Response.Output.Write(sb.ToString());
GridView3.AllowPaging = false;
GridView3.DataBind();
ExportDiv.RenderControl(oHtmlTextWriter);
string style = #"<style> TD { mso-number-format:\#; } </style>";
Response.Output.Write(oStringWriter.ToString());
Response.Write(style);
Response.End();
}
The good thing about the above code is it set HTML design and Grid view alignment accordingly.
Anyone else facing issue in this type of work can ask in comments
surely help him out.
I'm working on adding Export functionality to an existing site. I've created an Excel file, and I'm able to output it to my local directory, but when I try pushing the file to the user using Response, nothing happens. I've viewed several differnet articles and Stack questions, and none seem to be different from what I have, or work when I apply them.
Here is the code I currently have:
public void Export () {
//Create instance of the database
ExportContext eDB = new ExportContext();
var query = (from x in eDB.EMPLOYEES
select x);
IEnumerable<EMPLOYEES> employees = query.ToList();
//Set filename to Table + date/time
string fileName = "EMPLOYEES" + DateTime.Now.ToShortTimeString() + ".xlsx";
//Create excel package
ExcelPackage excel = new ExcelPackage();
var worksheet = excel.Workbook.Worksheets.Add("Employees");
worksheet.Cells[1, 1].LoadFromCollection(employees, true);
using (var memoryStream = new MemoryStream()) {
//Output the file to the user via download
Response.Buffer = false;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
Response.End();
}
}
Any help will be appreciated. Thanks.
I'm using the free version of NReco to convert html to pdf. The pdf is downloaded in default folder "Downloads". I need to customize it. Can anyone help me?
Thanks!
Edit:
The code that downloads the pdf in default folder was:
var pdfBytes = pdfConverter.GeneratePdf(strHtml);
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-Disposition", "attachment; filename=TEST.pdf");
Response.BinaryWrite(pdfBytes);
Response.TransmitFile(output_path_pdf);
Response.Flush();
Response.End();
This solution don't downloads the PDF as an attachment, but downloads it directly in the selected path, and it solves my problem.
string output_path_pdf = HttpContext.Server.MapPath("~/PDF_RESULT/" + fileName + ".pdf");
HtmlToPdfConverter pdfConverter = new HtmlToPdfConverter();
pdfConverter.PageWidth = 1000;
pdfConverter.PageHeight = 800;
pdfConverter.Margins = new PageMargins { Top = 0, Bottom = 0, Left = 0, Right = 0 };
pdfConverter.GeneratePdfFromFiles(new string[] { URL }, null, output_path_pdf);
I've developed a pdf file using itextsharp.
Pdf generation is working fine. After the pdf is created it's being downloaded.
My problem is when the user clicks on Generate PDF button , Pdf is generated and downloaded properly but postback doesn't occurs.
I want the postback to be occured because I want to Reset my Form after Pdf is generated that is Clear All Fields .
How Can I do this ?
Here is my code :
Method to Generate PDF :
public void GetPDF(string quote_num)
{
string url = FilesPath.Path_SaveFile + Session["empcd"].ToString() +"-Quotation.pdf";
Document disclaimer = new Document(PageSize.A4, 2, 2, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(disclaimer, new FileStream(url, FileMode.Create));
writer.PageEvent = new myPDFpgHandler(quote_num);
disclaimer.SetMargins(70, 10, 60, 80);
disclaimer.Open();
GenerateQuotPDF getpdf = new GenerateQuotPDF();
disclaimer = getpdf.GetPDFparams(disclaimer,quote_num, Session["empcd"].ToString(),txt_contactperson.Text,txt_contact1.Text,txt_company.Text,txt_address.Text,ddl_gene_desc.SelectedItem.ToString(),ddl_canopy.SelectedItem.ToString(),ddl_gene_type.SelectedItem.ToString(),txt_rentalamount.Text,txt_hours.Text,txt_variable.Text,ddl_terms.SelectedItem.ToString(),txt_remarks.Text,txt_technical.Text,ddl_sign1.SelectedValue,ddl_sign2.SelectedValue,txt_designation.Text,DateTime.Now);
disclaimer.Close();
System.IO.FileInfo file = new System.IO.FileInfo(url);
if (file.Exists)
{
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(url);
Response.AddHeader("content-disposition", "attachment; filename=" + Session["empcd"].ToString() + "-Quotation.pdf");
Response.AddHeader("content-length", buffer.Length.ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(buffer);
}
}
Generate PDF Button Code :
protected void btn_submit_Click(object sender, EventArgs e)
{
if (IsValidQuotation())
{
string newQuotNum = rental_quotations.GetNewQuotNumber();
rental_quotations.AddNewQuotation(newQuotNum, Session["empcd"].ToString(), ddl_gene_type.SelectedValue.ToString(), ddl_gene_desc.SelectedValue, ddl_canopy.SelectedValue, txt_company.Text, txt_address.Text, txt_contactperson.Text, txt_designation.Text, txt_contact1.Text, txt_contact2.Text, txt_rentalamount.Text, ddl_terms.SelectedValue, txt_hours.Text, txt_variable.Text, txt_remarks.Text,ddl_sign1.SelectedValue,ddl_sign2.SelectedValue,txt_technical.Text);
GetPDF(newQuotNum);
ClearAllFields(); //this is not working
}
}
Postback is occurring since the file is being created. Try the given solution. Your GetPDF(string quote_num) function is doing two tasks that you should break into two functions.
Creating the pdf document.
Downloading the pdf file after it is done.
Now, After you have created the document, you should clear the controls and then send the file as response. Therefore do it as follows:
Create pdf file.
public void CreatePDF(string quote_num)
{
string url = FilesPath.Path_SaveFile + Session["empcd"].ToString() +"-Quotation.pdf";
Document disclaimer = new Document(PageSize.A4, 2, 2, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(disclaimer, new FileStream(url, FileMode.Create));
writer.PageEvent = new myPDFpgHandler(quote_num);
disclaimer.SetMargins(70, 10, 60, 80);
disclaimer.Open();
GenerateQuotPDF getpdf = new GenerateQuotPDF();
disclaimer = getpdf.GetPDFparams(disclaimer,quote_num, Session["empcd"].ToString(),txt_contactperson.Text,txt_contact1.Text,txt_company.Text,txt_address.Text,ddl_gene_desc.SelectedItem.ToString(),ddl_canopy.SelectedItem.ToString(),ddl_gene_type.SelectedItem.ToString(),txt_rentalamount.Text,txt_hours.Text,txt_variable.Text,ddl_terms.SelectedItem.ToString(),txt_remarks.Text,txt_technical.Text,ddl_sign1.SelectedValue,ddl_sign2.SelectedValue,txt_designation.Text,DateTime.Now);
disclaimer.Close();
}
Reset the controls.
ClearAllFields();
Send the file as response.
public void SendPDF(string url)
{
System.IO.FileInfo file = new System.IO.FileInfo(url);
if (file.Exists)
{
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(url);
Response.AddHeader("content-disposition", "attachment; filename=" + Session["empcd"].ToString() + "-Quotation.pdf");
Response.AddHeader("content-length", buffer.Length.ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(buffer);
Response.End();
}
}
Note that I also added Response.End() to clear the buffer.
I am trying to download multiple pdf's as attachments in my asp.net application.I have created some templates and filling values using pdfstamper(itextsharp). I am able to fill the values but not able to download.
private void FillForm(string path, DataTable BridgeValues, DataTable Comments, DataTable Maintenance,string Newfilename)
{
try
{
string pdfTemplate = path;
string newFile = Newfilename;
string Pathser = "";
if (!System.IO.Directory.Exists(Server.MapPath(#"~/PDF/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(#"~/PDF/"));
}
if (Directory.Exists(Server.MapPath(#"~/PDF/")))
{
Pathser = Server.MapPath(#"~/PDF/" + Newfilename);
}
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
// create a new PDF reader based on the PDF template document
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(Pathser, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
DataColumn dc = null;
for (int i = 0; i < BridgeValues.Columns.Count - 1; i++)
{
dc = BridgeValues.Columns[i];
pdfFormFields.SetField(dc.ColumnName.ToString(), BridgeValues.Rows[0][dc].ToString());
}
pdfStamper.FormFlattening = true;
// close the pdf
pdfStamper.Close();
////Response.ContentType = "application/octet-stream";
Response.ContentType = "application/pdf";
////Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
Response.AddHeader("Content-Disposition", "attachment; filename=" + Newfilename + "");
////Response.BinaryWrite(mStream.ToArray());
Response.TransmitFile(Server.MapPath(("~/PDF/"+ Newfilename)));
Response.Clear();
Response.End();
}
catch (System.Threading.ThreadAbortException lException)
{
// do nothing
}
}
First time I tried to create one pdf ,it worked but later when I tried to download multiple files it gave an execption.
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
I don't think you can download multiple files by making one request and returning a collection from the action. I would suggest that it you need to allow user to download multiple files you ZIP them and stream the archive down to the browser.
Here is an example of zipping multiple files: http://devpinoy.org/blogs/keithrull/archive/2008/01/25/how-to-create-zip-files-in-c-with-sharpziplib-ziplib.aspx