ASP.Net page export to pdf - asp.net

I got stuck with my ASP.Net export to PDF. Below are my codes. Please help.
Response.Clear();
Response.Buffer = true;
Response.Charset = Encoding.UTF8.HeaderName;
Response.ContentEncoding = Encoding.UTF8;
Response.Write(string.Format("<meta http-equiv=Content-Type content=text/html;charset={0}>", Encoding.UTF8.HeaderName));
Response.ContentType = "application/pdf";
Response.Headers.Add("Content-disposition", "attachment; filename=pdffilename.pdf");
StringBuilder sb = new StringBuilder();
sb.Append("MIME-Version: 1.0\r\n");
sb.Append("X-Document-Type: Worksheet\r\n");
sb.Append("Content-Type: multipart/related; boundary=\"----=mtrSystem\"\r\n\r\n\r\n");
sb.Append("------=mtrSystem\r\n");
sb.Append("Content-Type: text/html; charset=\"utf-8\"\r\n");
sb.Append("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n");
sb.Append("xmlns:x=\"urn:schemas-microsoft-com:office:pdf\">\r\n\r\n\r\n");
sb.Append("------=mtrSystem\r\n");
sb.Append("Content-ID: baiduimg\r\n");
sb.Append("Content-Transfer-Encoding: base64\r\n");
sb.Append("Content-Type: image/png\r\n\r\n");
Can i use this way to export my ASP.Net page to PDF?

Html-to-pdf.net allows for converting html to pdf. TO get the html from an asp.net page, use the following code:
StringWriter sw = new StringWriter();
Server.Execute("PageToConvert.aspx", sw);
string htmlCodeToConvert = sw.GetStringBuilder().ToString();
Then pass the html to the pdf generator:
public byte[] GetPdfBytesFromHtmlString (string htmlString)
You can then save the bytes to the response to send to client, or save on the server as a local file.
EDIT:
Something to keep in mind, html-to-pdf does cost money, but for my last project it was a justified expense. You can use the trial version to figure out what you needd.

I'm not entirely sure what you're trying to do, but generally I can highly recommend PDFSharp for creating PDF documents in code...

Related

Download xml with its xsl file

I want to download xml file along with xsl(stylesheet).
My code for downloading xml file is as below:
XPathDocument myXPathDoc = new XPathDocument("myxml.xml");
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load("myxsl.xsl");
XmlTextWriter myWriter = new XmlTextWriter("Result.html", null);
myXslTrans.Transform(myXPathDoc, null, myWriter);
string strFullPath = Server.MapPath("Result.html");
string strContents = null;
System.IO.StreamReader objReader = default(System.IO.StreamReader);
objReader = new System.IO.StreamReader(strFullPath);
strContents = objReader.ReadToEnd();
objReader.Close();
//attach that XML file and download on local machine
string attachment = "attachment; filename=" + myWriter;
Response.ClearContent();
Response.ContentType = "text/html";
Response.AddHeader("content-disposition", attachment);
Response.Write(strContents);
I have searched in google, but not able to find a solution. Give some idea regarding this
But its giving exception like
The process cannot access the file '~mypath\Result.html' because it is being used by another process.
Do you want to write the xml to the response, or the xml with the xsl applied to it? If it is the latter, check this link:
Applying XSLT to XML in C#
If you want to just return the raw XML, then your code seems to be doing that already. However, the title of your question is a little misleading because you indicate you want to download 2 files with 2 request, which may be done with MIME but I fail to see the use of this. If a client is requesting an XML and XSL file, why not just apply them together?
I have added one html file and done like below
string strFullPathXml = Server.MapPath("myxml.xml");
string strFullPathXsl = Server.MapPath("myxsl.xsl");
string strFullPathHtml = Server.MapPath("Result.html");
XPathDocument xPathDoc = new XPathDocument(strFullPathXml);
XslCompiledTransform xslTrans = new XslCompiledTransform();
xslTrans.Load(strFullPathXsl);
XmlTextWriter xWriter = new XmlTextWriter(strFullPathHtml, null);
xslTrans.Transform(xPathDoc, null, xWriter);
xWriter.Close();
Response.ContentType = "text/html";
Response.AppendHeader("Content-Disposition", "attachment; filename=Result.html");
Response.ClearContent();
Response.WriteFile(strFullPathHtml);
Response.Flush();
Response.End();
After that its downloading html file which is in human readable format.

What's the easiest way to convert a BMP to a PDF in ASP.net

What's the easiest way to convert a BMP file to a single page PDF using ASP.net? I'm going to generate the 8.5" x 11" BMP in Flash (which means I can manipulate it to make it as easy as possible), then use a POST to upload it to an ASP page, which will convert it to a PDF and redirect the user to the PDF. I don't want to add any margins or anything else, it will be laid out properly in the BMP for full-bleed.
Would it be easier to convert it to PDF in Flash, then upload?
Thanks!
You can use iTextSharp to create a PDF and insert the image into the document. This can be done all in memory with a final PDF produced to client.
The following is an MVC method, stripped for display, but should see how to do this.
[HttpGet]
public FileStreamResult Export(int? ID)
{
MemoryStream stream = new MemoryStream();
Document pdf = new Document();
PdfWriter writer = PdfWriter.GetInstance(pdf, stream);
pdf.Open();
PdfPTable tblImage = new PdfPTable(1);
tblImage.AddCell(Image.GetInstance(LogChart())); //The LogChart method returns image
pdf.Add(Image);
pdf.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Log.pdf");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");
}

How do I create an XML file with ASP.NET and have it prompt to download?

I'm currently trying to write data (client machine) into a xml file where the user can save. However, I want the users to be able to decide on where they want to save this written xml file. Is there any controls or codes that I can use to allow the users to save the file?.
Update:
is that right way to do?
**HttpContext.Current.Response.Write(xw.ToStroing()); <<< ??????**
HttpContext.Current.Response.End();
update:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
MemoryStream ms = new MemoryStream();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.AddHeader("Content-Disposition:", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
using (StringWriter sw = new StringWriter())
{
using (XmlWriter xw = XmlWriter.Create(ms, settings))
{
xw.WriteStartDocument();
xw.WriteStartElement("Name");
xw.WriteStartElement("Application");
................
......................
HttpContext.Current.Response.Write(xw.ToStroing());
HttpContext.Current.Response.End();
When you begin a file download, the client's browser will handle the file saving location.
If you want to force the file to download instead of open, add this HTTP header to your response:
Content-Disposition: attachment; filename="myFile.xml"
here is the link helps me :)
Where is the MemoryStream being used? You should pass the StringWriter to the XmlTextWriter constructor then Response.Write() the contents of the StringWriter
Add this after the Response.AddHeader line:
Response.ContentType = "application/octet-stream";
This will force download of files, regardless the file type.

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