I try to open a word document with c#.
When I open the document, the page is blocked after.
Here is the code :
HttpContext.Current.Response.Write(temp);
//HttpContext.Current.Response.End();
//HttpContext.Current.Response.Flush();
//HttpContext.Current.Response.Write(sw.ToString());
//HttpContext.Current.Response.clear();
//HttpContext.Current.Response.End();
//HttpContext.Current.Response.SuppressContent = true;
//HttpContext.Current.Response.Close();
//Response.Redirect(Page.Request.Url.AbsolutePath.Substring(0, Page.Request.Url.AbsolutePath.LastIndexOf("/")) + "/PIEditor.aspx?PostID=" + Request.Params["PostID"], true);`
//HttpContext.Current.Response.End();
As you see, I tried different options but without result, the window for opening or saving the document is displayed but I can't click on any buttons the page after. It looks like it is deactivated or stopped.
you can try GemBox.Document component to export Word document from ASP.NET application, if that is what you are trying to do.
Here is a sample C# code that should go in ASPX page code behind:
// Create a new empty document.
DocumentModel document = new DocumentModel();
// Add document content.
document.Sections.Add(new Section(document, new Paragraph(document, "Hello World!")));
// Microsoft Packaging API cannot write directly to Response.OutputStream.
// Therefore we use temporary MemoryStream.
using (MemoryStream documentStream = new MemoryStream())
{
document.Save(documentStream, SaveOptions.DocxDefault);
// Stream file to browser.
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats";
Response.AddHeader("Content-Disposition", "attachment; filename=Document.docx");
documentStream.WriteTo(Response.OutputStream);
Response.End();
}
Try the below code:
//create new MemoryStream object and add PDF file’s content to outStream.
MemoryStream outStream = new MemoryStream();
//specify the duration of time before a page cached on a browser expires
Response.Expires = 0;
//specify the property to buffer the output page
Response.Buffer = true;
//erase any buffered HTML output
Response.ClearContent();
//add a new HTML header and value to the Response sent to the client
Response.AddHeader(“content-disposition”, “inline; filename=” + “output.doc”);
//specify the HTTP content type for Response as Pdf
Response.ContentType = “application/msword”;
//write specified information of current HTTP output to Byte array
Response.BinaryWrite(outStream.ToArray());
//close the output stream
outStream.Close();
//end the processing of the current page to ensure that no other HTML content is sent
Response.End();
Related
I have a asp text box that displays XML information. It looks like an XML file. I need to be able to allow a user to download a file that is created from the text box contents. I am using the following C# code.
protected void btnDownload_Click(object sender, EventArgs e)
{
var fileInBytes = Encoding.UTF8.GetBytes(tXML.Text);
using (var stream = new MemoryStream(fileInBytes))
{
long dataLengthToRead = stream.Length;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput = true;
Response.ContentType = "text/xml"; /// if it is text or xml
Response.AddHeader("Content-Disposition", "attachment; filename=" + "yourfilename.xml");
Response.AddHeader("Content-Length", dataLengthToRead.ToString());
stream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
}
Response.End();
}
When I try to download it with Chrome, I get Failed - Network Error. When I try to download it with IE, it'll download, but when I view the contents all the "<" and ">" are stripped from it. I know it could be a security issue downloading some file types, but an XML file? Is there a better way to do this?
It looks like you've forgotten to rewind the memory stream before you write it's contents to the response
using (var stream = new MemoryStream(fileInBytes))
{
stream.Seek(0, SeekOrigin.Begin);
long dataLengthToRead = stream.Length;
...
But, as jdweng states, XML is just text and can be written directly to the response without the need for a MemoryStream.
Here is a way that was posted on the asp.net forums. It uses the XMLDocument object instead.
XmlDocument Doc = new XmlDocument();
XmlDeclaration dec = Doc.CreateXmlDeclaration("1.0", null, null);
Doc.AppendChild(dec);
XmlElement DocRoot = Doc.CreateElement("settings");
Doc.AppendChild(DocRoot);
XmlNode server = Doc.CreateElement("textbox1");
DocRoot.AppendChild(server);
server.InnerText = this.TextBox1.Text;
XmlNode server2 = Doc.CreateElement("textbox2");
DocRoot.AppendChild(server2);
server2.InnerText = this.TextBox2.Text;
Doc.Save(Application.StartupPath + "\\xmlfile.xml");
I am new to Aspose but I have successfully converted several file formats into PDF's but I am struck with HTML to PDF conversion. I am able to convert a HTML file into a PDF successfully but the CSS part is not rendering into the generated PDF. Any idea on this? I saved www.google.com as my input HTML file. Here is my controller code.
using Aspose.Pdf.Generator
Pdf pdf = new Pdf();
pdf.HtmlInfo.CharSet = "UTF-8";
Section section = pdf.Sections.Add();
StreamReader r = File.OpenText(#"Local HTML File Path");
Text text2 = new Aspose.Pdf.Generator.Text(section, r.ReadToEnd());
pdf.HtmlInfo.ExternalResourcesBasePath = "Local HTML File Path";
text2.IsHtmlTagSupported = true;
text2.IsFitToPage = true;
section.Paragraphs.Add(text2);
pdf.Save(#"Generated PDF File Path");
Am i missing something? Any kind of help is greatly appreciated.
Thanks
My name is Tilal Ahmad and I am developer evangelist at Aspose.
Please use new DOM approach(Aspose.Pdf.Document) for HTML to PDF conversion. In this approach to render external resources(CSS/Images/Fonts) you need to pass resources path to HtmlLoadOptions() method. Please check following documentation links for the purpose.
Convert HTML to PDF (new DOM)
HtmlLoadOptions options = new HtmlLoadOptions(resourcesPath);
Document pdfDocument = new Document(inputPath, options);
pdfDocument.Save("outputPath");
Convert Webpage to PDF(new DOM)
// Create a request for the URL.
WebRequest request = WebRequest.Create("https:// En.wikipedia.org/wiki/Main_Page");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Time out in miliseconds before the request times out
// Request.Timeout = 100;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https:// En.wikipedia.org/wiki/");
// Load HTML file
Document pdfDocument = new Document(stream, options);
options.PageInfo.IsLandscape = true;
// Save output as PDF format
pdfDocument.Save(outputPath);
Try using media attribute in each style tag
<style media="print">
and then provide the html file to your Aspose.Pdf Generator.
Try this.. This is working nice for me
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Pdf.lic");
var license = new Aspose.Html.License();
license.SetLicense("Aspose.Html.lic");
using (MemoryStream memoryStream = new MemoryStream())
{
var options = new PdfRenderingOptions();
using (PdfDevice pdfDevice = new PdfDevice(options, memoryStream))
{
using (var renderer = new HtmlRenderer())
{
using (HTMLDocument htmlDocument = new HTMLDocument(content, ""))
{
renderer.Render(pdfDevice, htmlDocument);
//Save memoryStream into output pdf file
}
}
}
}
content is string type which is my html content.
I've just added the iTextSharp XMLWorker nuget package (and its dependencies) to my project and I'm trying to convert the HTML from a string into a PDF file, even though no exceptions are being thrown, the PDF file is being generated with two blank pages. Why?
The previous version of the code was using just iTextSharp 5.5.8.0 with HTMLWorker and ParseList method, then I switched to
Here is the code I'm using:
public void ExportToPdf() {
string htmlString = "";
Document document = new Document(PageSize.A4, 40, 40, 40, 40);
var memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
htmlString = sbBodyMail.ToString();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, new StringReader(htmlString));
document.Close();
DownloadFile(memoryStream);
}
public void DownloadFile(MemoryStream memoryStream) {
//Clears all content output from Buffer Stream
Response.ClearContent();
//Clears all headers from Buffer Stream
Response.ClearHeaders();
//Adds an HTTP header to the output stream
Response.AddHeader("Content-Disposition", "attachment;filename=Report_Diagnosis.pdf");
//Gets or Sets the HTTP MIME type of the output stream
Response.ContentType = "application/pdf";
//Writes the content of the specified file directory to an HTTP response output stream as a file block
Response.BinaryWrite(memoryStream.ToArray());
//Response.Write(doc);
//sends all currently buffered output to the client
Response.Flush();
//Clears all content output from Buffer Stream
Response.Clear();
}
If I place document.Add(new Paragraph("Just a test")); right before document.Close(); the paragraph is rendered in the second page, but the rest of the document still is blank.
UPDATE
I've changed the HTML in the htmlString variable to just a DIV and a TABLE and it worked. So, now the question becomes: how do I know what part of the HTML is causing some error in the XMLWorker?
I've figured out that XMLWorkerHelper was having trouble with DIV width attribute (even set on style attribute) and unfortunately it doesn't throw any exception to help you on this.
I found this answer from iTextSharp's developer that says that centering a table isn't supported yet, so I'm assuming this is not supported too.
This is the code for downloading the file.
System.IO.FileStream fs = new System.IO.FileStream(Path+"\\"+fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] ar = new byte[(int)fs.Length];
fs.Read(ar, 0, (int)fs.Length);
fs.Close();
Response.AddHeader("content-disposition", "attachment;filename=" + AccNo+".pdf");
Response.ContentType = "application/octectstream";
Response.BinaryWrite(ar);
Response.End();
When this code is executed, it will ask user to open or save the file. Instead of this I need to open a new tab or window and display the file. How can I achieve this?
NOTE:
File won't necessary be located in the website folder. It might be located in an other folder.
Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
Response.BinaryWrite(fileContent);
And
<asp:LinkButton OnClientClick="openInNewTab();" OnClick="CodeBehindMethod".../>
In javaScript:
<script type="text/javascript">
function openInNewTab() {
window.document.forms[0].target = '_blank';
setTimeout(function () { window.document.forms[0].target = ''; }, 0);
}
</script>
Take care to reset target, otherwise all other calls like Response.Redirect will open in a new tab, which might be not what you want.
Instead of loading a stream into a byte array and writing it to the response stream, you should have a look at HttpResponse.TransmitFile
Response.ContentType = "Application/pdf";
Response.TransmitFile(pathtofile);
If you want the PDF to open in a new window you would have to open the downloading page in a new window, for example like this:
View PDF
this may help
Response.Write("<script>");
Response.Write("window.open('../Inventory/pages/printableads.pdf', '_newtab');");
Response.Write("</script>");
You have to create either another page or generic handler with the code to generate your pdf. Then that event gets triggered and the person is redirected to that page.
Here I am using iTextSharp dll for generating PDF file.
I want to open PDF file instead of downloading it.
So I am using below code which is working fine for me.
Now pdf file is opening in browser ,now dowloading
Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
Paragraph Text = new Paragraph("Hi , This is Test Content");
pdfDoc.Add(Text);
pdfWriter.CloseStream = false;
pdfDoc.Close();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.End();
If you want to download file,
add below line, after this Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Example.pdf");
you can return a FileResult from your MVC action.
*********************MVC action************
public FileResult OpenPDF(parameters)
{
//code to fetch your pdf byte array
return File(pdfBytes, "application/pdf");
}
**************js**************
Use formpost to post your data to action
var inputTag = '<input name="paramName" type="text" value="' + payloadString + '">';
var form = document.createElement("form");
jQuery(form).attr("id", "pdf-form").attr("name", "pdf-form").attr("class", "pdf-form").attr("target", "_blank");
jQuery(form).attr("action", "/Controller/OpenPDF").attr("method", "post").attr("enctype", "multipart/form-data");
jQuery(form).append(inputTag);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
return false;
You need to create a form to post your data, append it your dom, post your data and remove the form your document body.
However, form post wouldn't post data to new tab only on EDGE browser. But a get request works as it's just opening new tab with a url containing query string for your action parameters.
Use this code. This works like a champ.
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();
In ASP.NET 4.0 webforms, I'm trying to export a paged ListView control to an Excel file by un-paging the ListView's (trucks) datasource:
dsTrucks.EnablePaging = false;
For a non-paged ListView control, I can get it to work.
Here's the attempt to "un-page" and then export the ListView control:
// Nuke the current page.
Response.Clear();
// Setup the response header.
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Trucks.xls");
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
// Turn off view state.
this.EnableViewState = false;
// Create a string writer.
var stringWriter = new StringWriter();
// Create an HTML text writer and give it a string writer to use.
var htmlTextWriter = new HtmlTextWriter(stringWriter);
// Disable paging so we get all rows.
dsTrucks.EnablePaging = false;
// Render the list view control into the HTML text writer.
listViewTrucks.DataBind();
listViewTrucks.RenderControl(htmlTextWriter);
// Grab the final HTML out of the string writer.
string output = stringWriter.ToString();
// Write the HTML output to the response, which in this case, is an Excel file.
Response.Write(output);
Response.End();
There's no error but the output in the Excel file is still just one page of the ListView control instead of all rows.
Any ideas on where to start to get this to work?
Thanks,
Adam
Just a guess, but it might be that EnablePaging works only on the control's OnInit() and it is too late by the time you call it from your code.
Perhaps you could you set the PageSize some MAXINT value and force all results into one single page?