Docx.dll SaveAs method throws exception - docx

we have used codeplex for saving docx on a network path.
But intermittently the SaveAs(string path) function of this dll fails.
the path provided to the function is as expected.
Thanks in advance.

This is the code I use to create and download docx document:
DocX g_document;
g_document = WhitePageReport(dt, dtSub);
MemoryStream ms = new MemoryStream();
g_document.SaveAs(ms);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=\"WhitePageReport.doc\"");
Response.ContentType = "application/msword";
ms.WriteTo(Response.OutputStream);
Response.End();

Related

Unable to open PDF after it's generated (vb.net) (asp.net)

Sorry for this question, but I'm new in .net and vb.net. I really need your help! I generate a PDF file in asp.net (vb.net). It should be opened in a browser automatically, but it gives an error - Failed to load PDF document. I see it's created on a drive and opens properly. What could be an issue?
Protected Sub ExportToPDF(sender As Object, e As EventArgs)
Response.ContentType = "application/pdf"
Dim pdfDoc As New Document(PageSize.A4, 50.0F, 10.0F, 10.0F, 10.0F)
PdfWriter.GetInstance(pdfDoc, New
FileStream(Context.Server.MapPath("~/ejik.pdf"), FileMode.CreateNew))
pdfDoc.Open()
pdfDoc.Add(New Paragraph("What is going on?"))
pdfDoc.Close()
Response.Write(pdfDoc)
Response.End()
End Sub
Thank you in advance!
P.S.: Sorry, I forgot to mention that I use iTextSharp to create a PDF
Your code is all wrong. You are creating a web application, and you create an object of type Document so that you can write a PDF file to disk. (Do you even need that file on disk? You are writing a web application!) Then, instead of sending the file to the end user, you write a Document object to the Response instead of (the bytes of) the file. That can never work, can it?
It would be better if you created the PDF file in memory first:
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(Assinatura());
document.Close();
Then you take the bytes of that file in memory, and send them to the Response:
byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=ejik.pdf");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
This is what the comment meant. Instead of pdfDoc, you need to send the byte array of the PDF file. See also iTextSharp is producing a corrupt PDF with Response

Getting jibberish when attempting to open DOCX in a browser

Using a memory stream & the correct MIME type with Response.ContentType. Special characters are displayed instead of prompting to open a Word document. I'm using:
using (MemoryStream ms = new MemoryStream())
{
doc.SaveAs(ms);
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
ms.WriteTo(Response.OutputStream);
Response.End();
}
Here's an example of the output I get now rather than a prompt to open a Word document:
Turns out it was not a MIME or Response.ContentType issue at all. Being an MVC application, I was attempting to open the FileResult in a modal. Copy/Paste fail, as other buttons worked this way to display content. Not a Word document!

"Thread is terminated" runtime error when initiating download

The situation:
In a C# web site project I am getting data out of a database and write the required data to an excel file server side, which I then want to offer for downloading.
The problem:
At the end of the code to initiate a download (See below) I get a runtime error that the thread is terminated and no file is offered for downloading.
My code
FileStream fStream = new FileStream(resultFile, FileMode.Open, FileAccess.Read);
byte[] byteBuffer = new byte[(int)fStream.Length];
fStream.Read(byteBuffer, 0, (int)fStream.Length);
fStream.Close();
response.Clear();
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Length", byteBuffer.Length.ToString());
response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(resultFile));
response.TransmitFile(resultFile);
response.End();
I hope somebody can help me with this. Thanks in advance :)
I used following code to download Excel
FileStream fs = File.OpenRead(path);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, (int)fs.Length);
Response.Buffer = true;
Response.ContentType = "application/x-msdownload";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName );
Response.BinaryWrite(data);

Export Repeater to excel

I am trying to export my repeater to excel and here is my code...
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
string attachment = "attachment; filename=file.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
rpt.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();
When I am trying to open file getting this error
The file you are trying to open, 'file.xls', is in a different format than specified
by the file extension. Verify that the file is not Corrupted and is from a trusted
source before opening the file. Do you want to open the file now?
Yes No Help option are available
What's wrong in my code or What I have to do resolve this issue.
Thanks
You are setting the content type to application/vnd.ms-excel but you are sending HTML contents in the response stream when you call the RenderContents method. You might need a library to generate Excel files.
Try wrapping your content into this:
StringBuilder sb = new StringBuilder("");
sb.Append("<HTML xmlns:x=\"urn:schemas-microsoft-com:office:excel\"><HEAD>");
sb.Append("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
sb.Append("<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>");
sb.Append(title);
sb.Append("</x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo/></x:Print></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--> </HEAD><BODY>");
sb.Append(content);
sb.Append("</BODY></HTML>");

ASP.NET stream content from memory and not from file

The users have requested the option to "download" a csv file representation of GridView contents. Does anyone know how to do this without saving the file to the server but rather just streaming it to the user from memory?
Thanks
Implement an IHttpHandler.
I used something similar to the following in the ProcessResponse for outputing a CSV that had previously been constructed in a database table...
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
//Get data to output here...
//Turn off Caching and enforce a content type that will prompt to download/save.
response.AddHeader("Connection", "close");
response.AddHeader("Cache-Control", "private");
response.ContentType = "application/octect-stream";
//Give the browser a hint at the name of the file.
response.AddHeader("content-disposition", string.Format("attachment; filename={0}", _filename));
//Output the CSV here...
foreach(BatchDTO.BatchRecordsRow row in dtoBatch.BatchRecords)
response.Output.WriteLine(row.Data);
response.Flush();
response.Close();
}
There are a number of libraries that make generating a CSV easier, you should just be able to pass it the Response.OutputStream to have it write to there rather than to a file stream.
Use context.Response.OutputStream.
Here's an example.
I created a StringBuilder and dump the contents to the Response object using the following code ("csv" is the StringBuilder variable).
Response.ContentType = #"application/x-msdownload";
Response.AppendHeader("content-disposition", "attachment; filename=" + FILE_NAME);
Response.Write(csv.ToString());
Response.Flush();
Response.End();
I have used the RKLib export library a few times to great effect, this uses a memory stream and can be given any datatable which it will export as a csv download:
http://www.codeproject.com/KB/aspnet/ExportClassLibrary.aspx

Resources