locked
How to preview customized word docx file in browser from MVC application RRS feed

  • Question

  • User1617707200 posted

    Hi,

    In my MVC Web application, I am generating one report as .Docx from a predefined template file using Xceed\DocX library. the docx file gets generated successfully and it gets saved in one folder in application path. But Now I want to display the generated document in browser as Preview feature. How can I achieve this? I was trying to convert the report doc to either PDF or HTML and then send it to browser but no success so far. Also  not getting any free tool/library suitable to convert the customized word docx file to these formats.

    Can anyone suggest a better option with which I can achieve both requirements: 1. Converting Docx to PDF or Html 2. Display the converted format in browser as Preview by sending the document through controller action. Like downloading and displaying file residing on app server to client machine.

    Any lead/help would be really grateful.

    Thanks In advance.

    Friday, June 26, 2020 7:33 PM

All replies

  • User1686398519 posted

    Hi Mayurib,

    According to your needs, I give a solution, please refer to it.

    • You need to add Microsoft.Office.Interop.Word through NuGet.
    • This solution converts word to html and then displays it.

    Controller

            public ActionResult Index()
            {
                return View();
            }
            public ActionResult openWord()
            {
                string FileName = "Test.docx";
                object documentFormat = 8;
                string randomName = DateTime.Now.Ticks.ToString();
                object htmlFilePath = Server.MapPath("~/Files/") + randomName + ".htm";
                object fileSavePath = Server.MapPath("~/Files/") + Path.GetFileName(FileName);
                _Application applicationclass = new Application();
                applicationclass.Documents.Open(ref fileSavePath);
                applicationclass.Visible = false;
                Document document = applicationclass.ActiveDocument;
                document.SaveAs(ref htmlFilePath, ref documentFormat);
                document.Close();
                string wordHTML = System.IO.File.ReadAllText(htmlFilePath.ToString());
                return Content(wordHTML);
            }

    Page

    @Html.ActionLink("openWord", "openWord", "Word", new { target = "_blank" })

    Here is the result.

     

    Best Regards,

    YihuiSun

    Monday, June 29, 2020 2:35 AM
  • User1617707200 posted

    Thanks for your reply @YihuiSun and sharing the solution. But I don't want to use Microsoft.Office.Interop as it requires Office to be installed on app server. My application is hosted in AWS VM. Sorry, I should have mentioned this in my post. Also from what I have learnt, Office interop is not recommended for Web apps. I am looking for any free tool / open source library that can give this feature. I am currently using OpenXMLPowerTool's HtmlConverter to convert Docx to Html but with this it does not copy/apply same docx formatting to the generated Html. If anyone could suggest a suitable tool/library to achieve this it will be good. Or at least if there is any option to keep the formatting intact with OpenXmlPowerTool HtmlConverter..

    Another option would be to convert the docx into PDF!!! I can then easily view the pdf in browser.

    Help for any of the option would be appreciable.

    Thanks 

    Monday, June 29, 2020 9:11 AM
  • User1686398519 posted

    Hi Mayurib,

    "DocToPDFConverter" can convert word to pdf.You can add "DocToPDFConverter" through Nuget. For specific usage, please refer to the example I gave.

    Controller

            public ActionResult Index()
            {
                return View();
            }
            public ActionResult openWord()
            {
                string fullpath = Server.MapPath("~/Files/Test.docx");
                byte[] FileBytes = System.IO.File.ReadAllBytes(ConvertWordToPdf(fullpath));
                return File(FileBytes, "application/pdf");
            }
            public string ConvertWordToPdf(string fullpath)
            {
                WordDocument wordDocument = new WordDocument(fullpath, FormatType.Docx);
                DocToPDFConverter converter = new DocToPDFConverter();
                PdfDocument pdfDocument = converter.ConvertToPDF(wordDocument);
                converter.Dispose();
                wordDocument.Close();
                string path = Path.Combine(Server.MapPath("~/Files"), "DocToPDF.pdf");
                pdfDocument.Save(path);
                pdfDocument.Close(true);
                return path;
            }

    Page

    @Html.ActionLink("openWord", "openWord", "Word", new { target = "_blank" })

    Here is the result.

     

    Best Regards,

    YihuiSun

    Wednesday, July 1, 2020 10:00 AM
  • User348806598 posted

    I was trying to convert the report doc to either PDF or HTML and then send it to browser but no success so far.

    Have one question. Why you need to convert it to PDF or HTML and see the preview in the browser. If you have the generated .docx file in the server. You can simply download the file, and the user can see the .docs file itself. But converting it into pdf or HTML may not preserve the styling that word file has. 

    Wednesday, July 1, 2020 10:10 AM
  • User1617707200 posted

    Yes, Final action on the document would be downloading on client machine. But before download, customer wants a Preview of the generated report(exported document) so that they can make corrections if required before downloading final version of the report. 

    Wednesday, July 1, 2020 11:10 AM
  • User348806598 posted

    Ok, In that case, what you can do is use google docs preview feature like below-

    <!DOCTYPE html>
    <html>
        <head>
            <script>
                function displayInline(){
                    //Get this url from server
                    var fileFromServer = "https://file-examples.com/wp-content/uploads/2017/02/file-sample_100kB.doc";
                    document.getElementById("previewFrame").src = src="https://docs.google.com/gview?embedded=true&url="+fileFromServer
                }
            </script>
        </head>
        <body>
            <button onclick="displayInline(); return false;">Display preview</button>
            <iframe id="previewFrame" frameborder="0" width="500" height="500"></iframe>
        </body>
    </html>

    Generate a URL (fileFromServer) in your server that you can browse in the current user session. And then you can use this URL for preview. Though you will not be able to edit the document in iframe.

    Wednesday, July 1, 2020 11:42 AM
  • User1617707200 posted

    Thanks for the solution. I tried it but its not displaying the docx file in iframe. It says Preview not available.

    Actually I dont want to open/preview the file in the same page. I want to show it either in a modal popup or in new browser tab but both not working. Here is my code on Preview button click

    1. using google docs viewer in popup

    var reporturl = docx file url from server
    $("#reportPreviewFrame").src = "https://docs.google.com/gview?url=" + reporturl + "&embedded=true";
    $('#dvPreviewReport').modal('show');

    reportPreviewFrame iFrame id inside the modal div dvPreviewReport

    2. using window.open

    var iWidth = 1400;
    var iHeight = 800;
    var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
    //Get the horizontal position of the window
    var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
    window.open(reporturl, '_blank', 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no');

    Wednesday, July 1, 2020 8:01 PM
  • User1686398519 posted

    Hi Mayurib,

    Can "DocToPDFConverter" solve your problem? Or do you have other requirements?

    Best Regards,

    YihuiSun

    Thursday, July 2, 2020 5:20 AM
  • User348806598 posted

    This should work.

    Please make sure you are able to access the generated docs file in the browser through your website.

    Also, it may not work on local, as google doc preview is not able to find the generated URL from your local system. It should work when you deploy to a public site.

    Thursday, July 2, 2020 6:42 AM
  • User1617707200 posted

    I did not get any free tool as 'DocToPDFConverter' when I tried searching in 'Manage NuGet packages for Solution' window. the one it showed in search list was Syncfusion's tool: Syncfusion.DocToPDFConverter.AspNet and it is not free, its paid one. And even if we use free version, there are limitations to it. So cannot use it.

    Are you talking about any other 'DocToPDFConverter'  tool that is free?

    Thanks.

    Thursday, July 2, 2020 12:29 PM