Hi,

Need some help with an problem that bugging me..

I have to open a .doc file at the client side when the user clicks a button.

Opening is not a problem.. I am able to do it using the following code
which is executed when the user clicks on the button

my code:

byte[] imagecontent = (byte[])(drd[0]);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + drd.GetValue(1).ToString());
Context.Response.BinaryWrite(imagecontent);

The problem is that the user first sees a 'Open/ Save / Cancel' dialog box. Only when the user clicks on 'Open' does the .doc file get opened.

I am using following code but it does not working.

String strPop = "<script language='javascript'>" + Environment.NewLine +
"window.open('E:\MyWork\Test\DownloadFiles\Reports\Rpt.pdf"','Report','height=520,width=730,toolbars=no,scrollbars=yes,resizable=yes');" + Environment.NewLine +
"</script>" + Environment.NewLine;
Page.RegisterStartupScript("Pop", strPop);

Am at a loss and any help will be appreciated.

Thanks

Dani AI

Generated

the browser prompt is happening because you are telling the browser to download. Use a view intent and the right MIME type for Word, but know this only hints the browser; it does not force it to open without a prompt. The user agent decides whether it can render inline or must download, per the HTTP spec for Content-Disposition. (rfc-editor.org)

If you want the best chance of an in-tab view, stream the file with the correct media type and an inline disposition. Also, do not try to open E:\... from JavaScript; that is a server path the client cannot access. Serve the file via an HTTP endpoint and let the server stream it.

// Example: stream a Word file inline from ASP.NET
void SendWord(byte[] bytes, string fileName)
{
    Response.Clear();
    bool isDocx = Path.GetExtension(fileName)
        .Equals(".docx", StringComparison.OrdinalIgnoreCase);

    Response.ContentType = isDocx
        ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        : "application/msword";

    string escaped = Uri.EscapeDataString(fileName);
    Response.Headers["Content-Disposition"] =
        $"inline; filename=\"{fileName}\"; filename*=UTF-8''{escaped}";
    Response.Headers["Content-Length"] = bytes.Length.ToString();

    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();
}

Those MIME types are the registered Word types; using application/octet-stream encourages download prompts. (developer.mozilla.org)

Reality check: most modern browsers cannot render a .doc/.docx natively, so even with the headers above many users will still see a download or an external app open. If you truly need an in-browser experience without prompts, render a PDF server-side and stream it inline, or hand off to an installed Office app using the ms-word: URI scheme (e.g., open-for-view/edit), which will launch Word if present. (learn.microsoft.com)

is spot on about using inline; if your end goal is a seamless viewer, PDF is the most predictable path today.

Recommended Answers

All 3 Replies

The "attachment" in your content-disposition instructs the browser to prompt for saving. The desired behavior you're describing is inline:

if (view)
            Response.AddHeader("Content-Disposition", "inline; filename = " + file.OriginalFileName);
          else
            Response.AddHeader("Content-Disposition", "attachment; filename = " + file.OriginalFileName);
public static void ServeAsPDF(System.Web.UI.Page webPage, Boolean download, String FileName)
    {
        try
        {
            string htmlString = GetHtmlForPage(webPage);
 
            webPage.Response.Buffer = true;
            webPage.Response.Clear();
            webPage.Response.ContentType = "application/vnd.ms-word"; //application/octet-stream
            webPage.Response.ContentEncoding = System.Text.UnicodeEncoding.UTF8;
            webPage.Response.Charset = "UTF-8";
            webPage.Response.AddHeader("Content-Disposition:", "attachment; filename="+ FileName +"");
            webPage.Response.AddHeader("cache-control", "must-revalidate");
            

            webPage.Response.Write("<html xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word'  xmlns:m='' xmlns='http://www.w3.org/TR/REC-html40'>");
            webPage.Response.Write("<head>");
            webPage.Response.Write("<title>PF FUND</title>");
            webPage.Response.Write("<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=UTF-8'>");
            webPage.Response.Write("<meta name=ProgId content=Word.Document>");
            webPage.Response.Write("<meta name=Generator content='Microsoft Word 9'>");
            webPage.Response.Write("<meta name=Originator content='Microsoft Word 9'>");
            webPage.Response.Write("<!--[if gte mso 9]> <xml> <w:WordDocument> <w:View>Print</w:View> <w:Zoom>100</w:Zoom> <w:DoNotOptimizeForBrowser/> </w:WordDocument> </xml> <![endif]-->");
            webPage.Response.Write("<style>");
            webPage.Response.Write("@page { size: 8.27in 11.69in; mso-page-orientation: Portrait Orientation; }");
            webPage.Response.Write("@page Section1 {margin:0.5in 0.5in 0.5in 0.5in;mso-paper-source:0;}");
            webPage.Response.Write("div.Section1 {page:Section1;}");
            webPage.Response.Write("@page Section2 {size:841.7pt 595.45pt;mso-page-orientation:landscape;margin:1.0in 1.0in 1.0in 1.0in;mso-header-margin:.5in;mso-footer-margin:.5in;mso-paper-source:0;}");
            webPage.Response.Write("div.Section2 {page:Section2;}");
            webPage.Response.Write("</style>");
            webPage.Response.Write("</head>");
            webPage.Response.Write("<body>");
            webPage.Response.Write("<div class=Section1>");
            webPage.Response.Write(htmlString);
            webPage.Response.Write("</div>");
            webPage.Response.Write("</body>");
            webPage.Response.Write("</html>");
            webPage.Response.Flush();
            webPage.Response.End();
        }
        catch
        {
            //Handle Exception
        }
    }
    public static string GetHtmlForPage(System.Web.UI.Page PgIn)
    {
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        Panel Panel1 = (Panel)PgIn.FindControl("Panel1");
        Panel1.RenderControl(htw);
        return sw.ToString();
    }

Hi, i used this code to generate word file from an aspx page. But my problem is, i need to generate pdf from this word file. So i want to read the word file, save it in byte array and render the bye array as PDF.

But this word file is generated on client side. I need to save this file on server, then read this word file and generate pdf so that user can view only PDF, not the word File..

Previously i tried to convert webpage to PDF but failed to do so..so i found it easy to generate a word file and then convert it into PDF ..
Please help me to accomplish this task..Its Urgent..!!!

Avinash,
Welcome to the forum! Please see DaniWeb's FAQ page, and note the 'Keep it Organized' section;-)
I'll post a response to a duplicate of your question, found here: [thread=381383]Save File to a given location without Open/Save Dialogue Box[/thread]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.