ASP.NET convert and download pdf using ClosedXML and Spire.XLS - c#

I use Web Forms. I try to convert ClosedXML excel workbook to pdf using Spire.XLS and download it by a client.
Here is my code:
protected void btnExport_OnClick(object sender, EventArgs e)
{
var excel = Reporting.GenerateExcel(); //custom, return XLWorkbook object
string myName = Server.UrlEncode(121 + "_" + DateTime.Now.ToShortDateString() + ".xlsx");
MemoryStream stream = GetStream(excel);
MemoryStream stream1 = new MemoryStream();
Workbook book = new Workbook();
book.LoadFromStream(stream);
book.SaveToStream(stream1, FileFormat.PDF);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + myName);
Response.ContentType = "application/pdf";
Response.BinaryWrite(stream1.ToArray());
Response.End();
}
public MemoryStream GetStream(XLWorkbook excelWorkbook)
{
MemoryStream fs = new MemoryStream();
excelWorkbook.SaveAs(fs);
fs.Position = 0;
return fs;
}
It seems like I receive not correct pdf. Thanks

Related

Shows warning message in exported xlsx file

My xlsx file is downloaded but when I open that xlsx file it shows warning as
'We found a problem with some content in'.
Can anyone tell me where I have to fix this? I am using an iFrame to download the file.
using (ClosedXML.Excel.XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt, "Sheet1");
Response.Clear();
Response.Charset = "";
Response.Buffer = true;
Response.BinaryWrite(bytes);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=" + >Model.reportName + "_" + DateTime.Now.ToString("yyyyMMddHH:mm") + "." + extension);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}

PDFsharp not giving pdf file in response

I am working on export functionality using PDFsharp in .Net MVC I am not getting any error in my code but not getting PDF file in response.
I have tried doing it manually writing it to specific path with the help of : System.IO.File.WriteAllBytes(path1, bytes); and it's working perfectly, but I am not getting PDF in Response with the help of
Response.BinaryWrite(bytes);
Response.OutputStream.Write(bytes, 0, bytes.Length);
Anyone have faced this type of issue or someone from community please help
Here is my code :
public bool ExportPdf(string htmlcontenttbl)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=Myfile.pdf");
Response.ContentType = "application/pdf";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
PdfDocument document =
PdfGenerator.GeneratePdf(htmlcontenttbl.ToString(), PdfSharp.PageSize.A4,
30);
var config = new PdfGenerateConfig();
config.PageOrientation = PageOrientation.Landscape;
config.PageSize = PageSize.A4;
config.MarginBottom = 30;
config.MarginTop = 30;
byte[] bytes = null;
using (MemoryStream stream = new MemoryStream())
{
document.Save(stream, true);
bytes = stream.ToArray();
}
var path1 = Server.MapPath("~/Images/" +
DateTime.Now.TimeOfDay.Ticks + "result.pdf");
//System.IO.File.WriteAllBytes(path1, bytes);
//Response.BinaryWrite(bytes);
//Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Flush();
Response.End();
return true;
}
thank you,

Getting value hexadecimal 0x02, character not valid

I am getting the following error:
, value hexadecimal 0x02, caracter not valid.
using this code:
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt1);
Response.Clear();
Response.Buffer = true;
Response.Charset ="";
Response.ContentType = "application/vnd.openxmlformats- officedocument.spreadsheetml.sheet";
//Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
I have tried different ways, but I still get the same error. "dt1" is filled from stored procedure.
to use ClosedXML I am currently doing the following and I call this method to open the Excel from a web page.
to call the ExportToExcel_SomeReport you would do it like this I create a public static class called Extensions
Extensions.ExportToXcel_SomeReport(dt1, fileName, this.Page);//Call the method on your button click
//this will be in the static public class you create
internal static void ExportToXcel_SomeReport(DataTable dt, string fileName, Page page)
{
var recCount = dt.Rows.Count;
fileName = string.Format(fileName, DateTime.Now.ToString("MMddyyyy_hhmmss"));
var xlsx = new XLWorkbook();
var ws = xlsx.Worksheets.Add("Some Custom Report");
ws.Style.Font.Bold = true;
ws.Cell("C5").Value = "Some Custom Header Report";
ws.Cell("C5").Style.Font.FontColor = XLColor.Black;
ws.Cell("C5").Style.Font.SetFontSize(16.0);
ws.Cell("E5").Value = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
ws.Range("C5:E5").Style.Font.SetFontSize(16.0);
ws.Cell("A7").Value = string.Format("{0} Records", recCount);
ws.Style.Font.Bold = false;
ws.Cell(9, 1).InsertTable(dt.AsEnumerable());
ws.Row(9).InsertRowsBelow(1);
// ws.Style.Font.FontColor = XLColor.Gray;
ws.Columns("1-8").AdjustToContents();
ws.Tables.Table(0).ShowAutoFilter = true;
ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
DynaGenExcelFile(fileName, page, xlsx);
}
private static void DynaGenExcelFile(string fileName, Page page, XLWorkbook xlsx)
{
page.Response.ClearContent();
page.Response.ClearHeaders();
page.Response.ContentType = "application/vnd.ms-excel";
page.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", fileName));
using (MemoryStream memoryStream = new MemoryStream())
{
xlsx.SaveAs(memoryStream);
memoryStream.WriteTo(page.Response.OutputStream);
memoryStream.Close();
}
page.Response.Flush();
page.Response.End();
}

downloaded pdf file not opening

I am saving a pdf file in the database by the following code
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string filetype = Path.GetExtension(FileUpload1.PostedFile.FileName);
int filesize = FileUpload1.PostedFile.ContentLength;
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
byte[] content = br.ReadBytes((Int32)fs.Length);
Objects.Insert_FilesToDatabase(filename, filetype, content,filesize);
and then, Iam trying to save the file from the database by clicking the link thru the following code.
void lnkDownload_Click(object sender, EventArgs e)
{
string filetype = Objects.GetFileType(Convert.ToInt32(txtslno.Text.Trim()));
string filename=Objects.GetFileName(Convert.ToInt32(txtslno.Text.Trim()));
int filesize = Objects.GetFileLength(Convert.ToInt32(txtslno.Text.Trim()));
byte[] bytfile = new byte[filesize+1000];
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",attachment;filename="+filename+".pdf");
Response.BufferOutput = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytfile);
Response.End();
}
Thru this code, I am able to download the pdf file but I am unable to open the pdf file. The error is the file is not decoded properly. Can you help me as to where am I going wrong?
I solved this problem thru the following code..
byte[] bytfile = Objects.GetFile(Convert.ToInt32(txtslno.Text.Trim()));
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename="+filename);
Response.AddHeader("Content-Length", bytfile.Length.ToString());
Response.OutputStream.Write(bytfile, 0, bytfile.Length);
Response.Flush();
Response.End();
I am just not writing the binary content to the output pdf stream in my previous code..
Thank you for your support

How to write FDF to PDF using iTextSharp c#

I have this example to fill a FDF programmatically and to visualize it.
private readonly string pdfFormFileName = "PDFForm.pdf";
protected void OpenPDF_Click(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "application/vnd.fdf";
FdfWriter fdfWriter = new FdfWriter();
fdfWriter.File = GetAbsolutePath() + pdfFormFileName;
fdfWriter.SetFieldAsName("txtFirstName", FirstName.Text);
fdfWriter.SetFieldAsName("txtLastName", LastName.Text);
Response.AddHeader("Content-disposition", "inline; filename=FlatPDFForm.fdf");
fdfWriter.WriteTo(Response.OutputStream);
Response.End();
}
Instead of displaying the file, I need to save it to a file.
Could you pls help me?
I found the solution!
string newFile = Server.MapPath("~/") + "ModF23_Final.pdf";
string pdfTemplate = Server.MapPath("~/") + "ModF23.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.SetField("2", FirstName.Text);
pdfFormFields.SetField("2-1", LastName.Text);
pdfStamper.FormFlattening = true;
pdfStamper.Close();
Andrea could you try using this line of code
Response.ClearHeaders();
Response.ContentType = "application/vnd.fdf";
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment;Filename=FlatPDFForm.fdf");
Response.TransmitFile("FlatPDFForm.fdf");
Response.End();
Comment out this line fdfWriter.WriteTo(Response.OutputStream);
ADDED correct ContentType

Categories