Click here to Skip to main content
14,427,368 members
Rate this:
Please Sign up or sign in to vote.
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="">
<head runat="server">
    <script type="text/javascript">
        function doHighlight(DivText, searchTerm, highlightStartTag, highlightEndTag) {
            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) {
            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) {
            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);
    <form id="form1" runat="server">
        <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="submit" OnClick="btnUpload_Click" />
        <asp:TextBox ID="searchTxt" 
        <input type="button" value="Search" onclick="return searchPrompt('search text', 'dvWord', false, true, 'red', 'orange')" />
        <div id="dvWord" runat="server"></div>

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/")))

            //Upload the word document and save to Temp folder.

            //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.

            //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;
Updated 10-Jan-20 8:49am
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.
hertzogth 15-Jan-20 8:37am
For Word files (DOC, DOCX, RTF, etc.) you'll need to convert them to something that can be displayed in browser, like an image or HTML text.

For example, see here how to convert Word to HTML in C#.
Or see here how to create Word Editor in ASP.NET.

For PDF files, see here how to convert PDF to image.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

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

Another option might be the SyncFusion Document Editor component:[^]

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
OriginalGriff 5,128
Richard MacCutchan 1,804
phil.o 1,270
Patrice T 1,217
MadMyche 1,110

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100