Click here to Skip to main content
15,896,726 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Hello Members,

Hope you are doing good!!

Can any one guide me on preview of doc,docx and PDF documents using ASP.NET and C#.

Here i am added the code.

What I have tried:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LoadingWordDocument.aspx.cs" Inherits="WordDocumentLoadSampleWebApp.LoadingWordDocument" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function doHighlight(DivText, searchTerm, highlightStartTag, highlightEndTag) {
            debugger;
            if ((!highlightStartTag) || (!highlightEndTag)) {
                highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
                highlightEndTag = "</font>";
            }

            var newText = "";
            var i = -1;
            var lcSearchTerm = searchTerm.toLowerCase();
            var lcDivText = DivText.toLowerCase();

            while (DivText.length > 0) {
                i = lcDivText.indexOf(lcSearchTerm, i + 1);
                if (i < 0) {
                    newText += DivText;
                    DivText = "";
                } else {
                    if (DivText.lastIndexOf(">", i) >= DivText.lastIndexOf("<", i)) {
                        if (lcDivText.lastIndexOf("/script>", i) >= lcDivText.lastIndexOf("<script", i)) {
                            newText += DivText.substring(0, i) + highlightStartTag + DivText.substr(i, searchTerm.length) + highlightEndTag;
                            DivText = DivText.substr(i + searchTerm.length);
                            lcDivText = DivText.toLowerCase();
                            i = -1;
                        }
                    }
                }
            }

            return newText;
        }
                                
        function highlightSearchTerms(searchText, divId, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag) {
            debugger;
            if (treatAsPhrase) {
                searchArray = [searchText];
            } else {
                searchArray = searchText.split(" ");
            }
            var div=document.getElementById(divId);
            if (!div || typeof (div.innerHTML) == "undefined") {
                if (warnOnFailure) {
                    alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
                }
                return false;
            }

            var DivText = div.innerHTML;
            for (var i = 0; i < searchArray.length; i++) {
                DivText = doHighlight(DivText, searchArray[i], highlightStartTag, highlightEndTag);
            }

            div.innerHTML = DivText;
            return true;
        }

        function searchPrompt(defaultSearchText, divId, isPrompt, treatAsPhrase, textColor, bgColor) {
            debugger;
            if ((!textColor) || (!bgColor)) {
                highlightStartTag = "";
                highlightEndTag = "";
            } else {
                highlightStartTag = "<font style='color:" + textColor + "; background-color:" + bgColor + ";'>";
                highlightEndTag = "</font>";
            }

            return highlightSearchTerms(searchTxt.value, divId, false, true, highlightStartTag, highlightEndTag);
        }
     </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="submit" OnClick="btnUpload_Click" />
        <div></div>
    </div>
        <div>
        <asp:TextBox ID="searchTxt" 
            runat="server" 
            Width="300px" 
            Height="25px" 
            Font-Size="Medium"></asp:TextBox>
        <input type="button" value="Search" onclick="return searchPrompt('search text', 'dvWord', false, true, 'red', 'orange')" />
    </div>
        <div id="dvWord" runat="server"></div>
    </form>
</body>
</html>

CS file
<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Word;
using System.IO;
using System.Text.RegularExpressions;

namespace WordDocumentLoadSampleWebApp
{
    public partial class LoadingWordDocument : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            object documentFormat = 8;
            string randomName = DateTime.Now.Ticks.ToString();
            object htmlFilePath = Server.MapPath("~/Temp/") + randomName + ".htm";
            string directoryPath = Server.MapPath("~/Temp/") + randomName + "_files";
            object fileSavePath = Server.MapPath("~/Temp/") + Path.GetFileName(FileUpload1.PostedFile.FileName);

            //If Directory not present, create it.
            if (!Directory.Exists(Server.MapPath("~/Temp/")))
            {
                Directory.CreateDirectory(Server.MapPath("~/Temp/"));
            }

            //Upload the word document and save to Temp folder.
            FileUpload1.PostedFile.SaveAs(fileSavePath.ToString());

            //Open the word document in background.
            _Application applicationclass = new Application();
            applicationclass.Documents.Open(ref fileSavePath);
            applicationclass.Visible = false;
            Document document = applicationclass.ActiveDocument;

            //Save the word document as HTML file.
            document.SaveAs(ref htmlFilePath, ref documentFormat);

            //Close the word document.
            document.Close();

            //Read the saved Html File.
            string wordHTML = System.IO.File.ReadAllText(htmlFilePath.ToString());

            //Loop and replace the Image Path.
            foreach (Match match in Regex.Matches(wordHTML, "<v:imagedata.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase))
            {
                wordHTML = Regex.Replace(wordHTML, match.Groups[1].Value, "Temp/" + match.Groups[1].Value);
            }

            dvWord.InnerHtml = wordHTML;
        }
    }
}
Posted
Updated 10-Jan-20 7:49am
Comments
Richard Deeming 10-Jan-20 11:36am    
Considerations for server-side Automation of Office[^]
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
Richard Deeming 10-Jan-20 11:37am    
Aside from the fact that your code almost certainly won't work, you haven't actually asked a question.

1 solution

Maybe the answers here will help you: open word document file in browser in asp.net[^]

Another option might be the SyncFusion Document Editor component: https://ej2.syncfusion.com/documentation/document-editor/[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900