I have tried a code to open a pdf file in a web browser. It give to allows me to open the file through pdf reader no in the browser. Almost all the codes i found over the internet are also same as this code. But this code doesn't work as i expected.
Help me to figure out the problem in here. I'm using a link button in the aspx.
Here is my code
aspx code
<asp:LinkButton ID="pdfViewLOP" runat="server" Style="margin-left: 10px" OnClick="pdfViewLOP_Click" >View PDF</asp:LinkButton>
aspx.cs
Response.Write(string.Format("<script>window.open('{0}','_blank');</script>", "viewPDF.aspx"));
Code of the new page which pdf should be displayed
string name=Session["name"].ToString();
int refNo = Convert.ToInt32(name);
string FilePath = Server.MapPath("~/filesPDF/" + refNo + ".pdf");
WebClient User = new WebClient();
Byte[] buffer = User.DownloadData(FilePath);
if (buffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
How if you directly create a hyperlink with target _blank and path of file as a href of hyperlink.
So the result hyperlink generated inside the html page is
View PDF
Related
I am using Nreco in mvc dotnet to export Html to Odt(Open office) file. But after getting exported image is not getting loaded in odt File. I have tried for Html to Pdf, which is working perfectly fine, but not in Html to Odt. Please look into the below code lines.
<div style="float:right; width:49%; text-align:right"><img
src="#(Url.Content("~/Content/img/logo.jpg"))" width="225"
height="44" alt="Logo" /></div>
Controller code:
HtmlToPdfConverter htmltoPdfObj = new HtmlToPdfConverter();
htmltoPdfObj.Orientation = PageOrientation.Default;
htmltoPdfObj.CustomWkHtmlArgs = "--margin-top 22 --header-spacing 10 --margin-bottom 20";
byte[] pdfContents = htmltoPdfObj.GeneratePdf(this.GetPDFScript() + htmlContractData + "</body></html>");
Response.Clear();
Response.Charset = "";
Response.ContentType = "application/vnd.oasis.opendocument.text";
string strFileName = "GenerateDocument" + ".odt";
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName);
Response.Write(htmlContractData);
Response.End();
htmlContractData > plane cshtml text with above div Image.
Please help me out with this Issue troubling me since long
I have tried two methods to open a zip file from internet explorer, but none works.
Method 1
<li>
IM User Guide
</li>
With this method, I can see the "Open" dialog box. If I click on "Open", it may be trying to open it. But the file is not opened.
Method 2
<li>
<asp:LinkButton ID="btnDownloadUserGuide" Text="IM User Guide" runat="server" Visible="true" OnClick="btnDownloadUserGuide_Click"></asp:LinkButton>
<asp:HiddenField ID="hdnUserGuide" runat="server" Value="~/HelpDocs/IMs_Guide.zip" /></li>
Code behind (Method 2)
protected void btnDownloadUserGuide_Click(object sender, EventArgs e)
{
if (!hdnUserGuide.Value.Trim().Equals(""))
{
//string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\HelpDocs\\IMs_Guide.zip";
string FilePath = HttpContext.Current.Server.MapPath("\\HelpDocs\\IMs_Guide.zip");
string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\HelpDocs\\IMs_Guide_to_New_Q-Track.zip";
Response.AppendHeader("content-disposition", "attachment; filename=" + "IMs_Guide.zip");
Response.AppendHeader("Cache-Control", "no-cache");
Response.ContentType = "Application/x-zip-compressed";
Response.WriteFile(FilePath);
//Response.End();
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
With this method, it may be trying to open it, but no "Open" dialog box is seen. File is not opened.
If attempt is made to save it instead of opening the file, that works.
The same issue is observed if the file type is changed to doc or pdf.
The same code (both methods) work in Chrome and Mozilla browsers.
I am exporting data into Excel from a web page. This should be a no brainer, but there are <p> tags in the data. This causes Excel to create new rows when the data should all be in the same cell. After some research I found that mso-data-placement should do the trick, but it's not working. Excel opens, the data is displayed, but extra uncessary rows are created. Here is the code I use to export the data:
protected void doexcel()
{
string style = #"<style type='text/css'>P {mso-data-placement:same-cell; font-weight:bold;}</style>";
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
//set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
Random RandomClass = new Random();
int RandomNumber = RandomClass.Next();
String filename = "a" + RandomNumber + DateTime.Now + ".xls";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"" );
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
HttpContext.Current.Response.Write(style);
SqlDataSourceEmployeeAssets.ConnectionString = MyObjects.Application.CurrentContext.ConnectionString;
String sql = (string)Session["sql"];
SqlDataSourceEmployeeAssets.SelectCommand = sql;
// lCount.Text = "Query returned " + getCount(query) + " rows.";
DataGrid dge = new DataGrid();
dge.DataSource = SqlDataSourceEmployeeAssets;
dge.DataBind();
dge.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
This is an example of the raw data in the database that is giving me grief:
<P>4/13/2011 : Cheng "Jonathan" Vaing is with BSES Graffiti Unit.</P><P>4/13/2011 : Cheng "Jonathan" Vaing is with</P>
Suggestions?
I tried a couple of other things
I went straight to the data and added the mso-data-placement attribute to the paragraph tag inline. Still didn't work. The data looked like this
<P style="mso-data-placement:same-cell> my data </p>
I tried other mso-* attributes, that didn't work either. For example, I changed my stylesheet to look like this
<style type='text/css'>P {mso-highlight:yellow}</style>";
Why oh why doesn't Excel recognize my mso-* attributes?!?!
There is a solution but it is not clean.
After the dge.DataBind, place the following code. This will encode the text of each cell
foreach (DataGridItem dgi in dge.Items)
{
foreach (TableCell cell in dgi.Cells)
{
cell.Text = WebUtility.HtmlEncode(cell.Text);;
}
}
The Excel file, when opened, should show the raw data with the markup, all in one cell.
I found that this works because Excel actually encodes the text, as well. To see what Excel does in action, do the following:
Create a new workbook in Excel (I am using Office 2013).
In the first cell, paste the raw data (as you have it displayed). Do this by first pressing F2 (insert into cell), then paste the text.
Save the workbook as an HTML file (or web page).
Using windows explorer, go to the folder location of where you saved the file. There should be a hidden folder (i think it is hidden) with the same name as your file. For example, if your workbook is Book1.htm, there should be a folder labeled Book1_files.
In this folder, there should be an HTM file with the name sheet001.htm. Open this file in notepad (or any text editor...not excel or word)
Locate your raw data. You will see that the text is not showing the HTML markup, rather it is showing the encoded version.
Hope this helps.
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();
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();