205

I have successfully done code to display a PDF file in the browser instead of the "Open/Save" dialog. Now, I'm stuck trying to display a Word document in the browser. I want to display a Word document in Firefox, IE7+, Chrome etc.

Can any one help? I am always getting the "Open/Save" dialog while displaying the Word doc in browser. I want to implement this functionality using JavaScript.

Mark
  • 1,294
  • 1
  • 14
  • 32
Pankaj
  • 2,713
  • 4
  • 13
  • 21
  • 1
    http://stackoverflow.com/questions/9418850/how-to-display-a-word-document-using-fancybox – Sadikhasan Jan 15 '15 at 06:19
  • 1
    you can use [syncfusion-document-editor](https://ej2.syncfusion.com/react/demos/document-editor/character-formatting/) in react for show and edit docx files – Yusuf Mohammad Feb 09 '20 at 06:28

12 Answers12

310

No browsers currently have the code necessary to render Word Documents, and as far as I know, there are no client-side libraries that currently exist for rendering them either.

However, if you only need to display the Word Document, but don't need to edit it, you can use Google Documents' Viewer via an <iframe> to display a remotely hosted .doc/.docx.

<iframe src="https://docs.google.com/gview?url=http://remote.url.tld/path/to/document.doc&embedded=true"></iframe>

Solution adapted from "How to display a word document using fancybox".

Example:

JSFiddle

However, if you'd rather have native support, in most, if not all browsers, I'd recommend resaving the .doc/.docx as a PDF file Those can also be independently rendered using PDF.js by Mozilla.

Edit:

Huge thanks to cubeguerrero for posting the Microsoft Office 365 viewer in the comments.

<iframe src='https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc' width='1366px' height='623px' frameborder='0'>This is an embedded <a target='_blank' href='http://office.com'>Microsoft Office</a> document, powered by <a target='_blank' href='http://office.com/webapps'>Office Online</a>.</iframe>

One more important caveat to keep in mind, as pointed out by lightswitch05, is that this will upload your document to a third-party server. If this is unacceptable, then this method of display isn't the proper course of action.

Live Examples:

Google Docs Viewer

Microsoft Office Viewer

Allart
  • 626
  • 6
  • 25
Brandon Anzaldi
  • 6,346
  • 3
  • 35
  • 52
  • As per your comment at client side it's not possible.And if I use http://docs.google.com/gview? then document must uploaded in google drive.Is it so? – Pankaj Jan 15 '15 at 07:51
  • 2
    @Pankaj You do not have to upload it to Google Drive. You can just change the `url` paramteter to the full URL to the .doc file, either hosted on your server, or anywhere it can be directly linked to. Google Docs handles the conversion to a format that can be handled by the browser on the fly, and does not require it to be uploaded or stored on Google Docs, instead performing a server-side request to grab the file. – Brandon Anzaldi Jan 15 '15 at 08:09
  • I have tried with below code But it will show me message 'Apologies There is no preview available' – Pankaj Jan 15 '15 at 08:16
  • 4
    @Pankaj Even if you're hosting a local server, Google cannot access `localhost`. It needs a publicly accessible URL. You could use a basic forwarding service like [Finch](https://meetfinch.com/). – Brandon Anzaldi Jan 15 '15 at 08:41
  • Ok.I understand.Thnaks for your valuable reply. – Pankaj Jan 15 '15 at 09:43
  • I have tried with giveURL "https://docs.google.com/gview?url=http://example.com/yyy/LocalData/Test.doc&embedded=true" but it will gives me an error message 'Apologies There is no preview available' why this so?Now 'example.com' has public URL – Pankaj Feb 18 '15 at 11:33
  • If Google's servers are unable to download the file, either by explicit blocking, or an incorrect path, it won't be able to render a preview. Also, if it's not a `.doc` file, that will likely also cause problems, since if you're actually using `example.com`, they don't have a document at that location from what I can tell. I was able to successfully test it with this URL: [https://docs.google.com/gview?url=http://ieee802.org/secmail/docIZSEwEqHFr.doc&embedded=true](https://docs.google.com/gview?url=http://ieee802.org/secmail/docIZSEwEqHFr.doc&embedded=true) – Brandon Anzaldi Feb 19 '15 at 01:00
  • Thanks for your reply.Actually when I hit the URL(https://example.com) in browser its ask for domain UserName and Password because of it show me an error message? when i try to open doc file using google doc viewer. – Pankaj Feb 19 '15 at 05:14
  • If it's using HTTP Basic Auth, you might be able to do `username:password@example.com`, although not for sure. Otherwise, you'll have to use a non-authenticated host for the .doc. – Brandon Anzaldi Feb 21 '15 at 09:51
  • 15
    You could also use the office live apps viewer: //view.officeapps.live.com/op/embed.aspx?src=your_url_here put this url in an iframe – cubeguerrero Jan 18 '16 at 09:36
  • fatbotdesigns, do you want to post an answer for that ? – Chris Neve Mar 01 '16 at 11:24
  • @ThomCunningham I incorporated it into my answer as well. – Brandon Anzaldi Mar 02 '16 at 07:56
  • My server can serve the doc file for MS office viewer but Google viewer can't read it. What am I doing wrong here? The URL I use look like this `http://docs.google.com/gview?url=https://domain.com/handler.ashx?id={id}` – Hp93 Oct 31 '16 at 13:54
  • @Hp93 You might get more help by asking a new question, and I can't offer much help from just seeing a URL. A few troubleshooting steps you can try: 1) Visit the URL manually in your browser and ensure it sends the document, 2) Double check the type of file. GDocs viewer can definitely render `.doc` and `.docx` files, but I'm unsure of other types of files, such as `.dot`, etc. – Brandon Anzaldi Oct 31 '16 at 19:13
  • It works only for .docx extenstion isn't it ? Can I open excel sheets, xmls or images using the same method in browser? – Jerry Mar 06 '17 at 11:30
  • @Jerry I was able to get it to work with a .xls sheet: https://docs.google.com/gview?url=http://spreadsheetpage.com/downloads/xl/time%20sheet.xls&embedded=true – Brandon Anzaldi Mar 06 '17 at 20:18
  • In my scenario google docs wont have access to my local files, what do i do here ?, i have to setup an intranet – Boniface Pereira Jul 16 '17 at 14:09
  • 1
    @BonifacePereira If you're setting up an intranet, you'll probably have to do some conversion locally, since GDocs and Live would both have to fetch the document from somewhere. If you're able to, you might be able to set up a server for conversion with OpenOffice or something: https://stackoverflow.com/questions/5538584/convert-word-doc-docx-and-excel-xls-xlsx-to-pdf-with-php#11665852 – Brandon Anzaldi Jul 17 '17 at 20:25
  • 45
    Just want to point out that both of these methods definitely upload the files to Google's and Microsoft's servers. If you are dealing with sensitive information that should have limited access- do not do this. Use the alternative solution with PDF.js to generate a PDF version of the file to view in the browser and offer a link to download the various excel/doc versions. – lightswitch05 Sep 28 '17 at 17:47
  • What about password protected files ? I mean the doc file accessible after user login. How can I preview them ? – Mohsen Zia Apr 08 '18 at 07:33
  • @MohsenZia If you want to preview them using either of these services, you're going to have to pass an unauthenticated link to the service, or (I still haven't had a chance to test if this works) use a basic auth URL. (E.g. `https://username:password@whatever.host/path/to/word.doc`). My recommendation is to render whatever docs you need into PDF, and serve them to the user through access controlled paths. – Brandon Anzaldi Apr 09 '18 at 21:57
  • @BrandonAnzaldi.. one silly question. browser can render pdf documents, then what is the use of PDF.js and other similar libraries? – Azima Apr 24 '18 at 14:48
  • @Azima In certain circumstances the browser will force you to download the PDF and open it separately rather than rendering it internally. Using a dedicated preview library makes it more consistent that your end-user will see the PDF preview instead of downloading it. – Charles Wood Jan 19 '19 at 17:30
  • @BrandonAnzaldi can you help how could i remove the bottom toolbar in this view. I just want the preview of a word – always-a-learner May 15 '20 at 11:46
  • @BrandonAnzaldi Is this solution still valid? Browsers seem to be complaining about Cross site cookies. Is there anyway to get around the cross site cookie issue? Warning from chrome: A cookie associated with a cross-site resource at http://live.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies – Asha Jun 02 '20 at 11:17
  • Can we embed keynote using Google and Microsoft @BrandonAnzaldi ?? – Rohit Kumar Jul 14 '20 at 12:51
  • 1
    This is incorrect. PDFTron WebViewer supports rendering of Word (and other Office formats) directly in the browser and without server side dependencies. To test, try https://www.pdftron.com/webviewer/demo/ – Ika Sep 03 '20 at 20:30
  • 4
    @lightswitch05 hey, just stumbled upon this, I have looked at pdf.js after reading your comment and couldnt find any documentation regaring the conversion of doc / xls files to pdf to display them within the browser, how would this work exactly? – stackg91 Nov 25 '20 at 15:11
  • 6
    we are in 2021 and still there's no solution to this, sadly! – Vinicius Dutra Feb 05 '21 at 19:29
  • @Ika PDFTron needs paid license, otherwise you will have PDFTron watermark on every pages of your document – mending3 Jul 15 '21 at 08:21
  • Just a question! What if, the file in (http://remote.url.tld/path/to/document.doc) can only be access by this client, will it be rendered? In another words. Is the file requested to the iframe from the browser! Or at officeapps or google doc site? Lets say this file need sort of an active session or security. – ALMEK Jan 18 '22 at 07:52
  • Remember to encode the URL of your file! As described in the [docs](https://www.microsoft.com/en-us/microsoft-365/blog/2013/04/10/office-web-viewer-view-office-documents-in-a-browser/) – Avi Kaminetzky Jan 26 '22 at 15:22
39

The answers by Brandon and fatbotdesigns are both correct, but having implemented the Google docs preview, we found multiple .docx files that couldn't be handled by Google. Switched to the MS Office Online preview and works likes a charm.

My recommendation would be to use the MS Office Preview URL over Google's.

https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc' 
kernelmann
  • 399
  • 3
  • 3
  • 1
    Is there any restriction to use this ? https://support.microsoft.com/en-us/help/2769380/file-not-found-error-message-when-you-try-to-open-an-office-file-from – Vishnu Feb 15 '18 at 07:03
  • to provide a counter narrative - we chose the google version because the microsoft renderer takes a lot longer to load in both chrome and ff – snerd Jul 24 '18 at 15:18
  • 1
    Is there similar service for previewing PDFs? – Igor Nikiforov Jul 23 '21 at 10:45
  • 1
    An error occurred We're sorry, but for some reason we can't open this for you. i got this error when used this – Varun Kumar Medam Aug 16 '21 at 13:25
25

There are a few js libraries that can handle .docx (not .doc) to html conversion client-side (in no particular order):

Note: If you are looking for the best way to convert a doc/docx file on the client side, then probably the answer is don't do it. If you really need to do it then do it server-side, i.e. with libreoffice in headless mode, apache-poi (java), pandoc etc.

ccpizza
  • 25,495
  • 13
  • 148
  • 149
  • 2
    I will note that my library is completely unmaintained. It was able to convert docx files to something that could be rendered in the browser. I don't know if this is true anymore. – artburkart Nov 09 '17 at 16:41
  • Why do you say "the answer is don't do it"? – Luke May 02 '22 at 16:35
  • @Luke because this is the kind of task that should preferably done serverside; doing it client-side is delegating too much responsibility to the client and making too many assumptions about the client's capabilities, performance, etc; ideally you'd want to have everything rendered on the server and delivered to the client in most efficient way, preferably in an easily cacheable format – ccpizza May 02 '22 at 17:26
6

A great solution if your data is confidential

Since the documents are confidential, they should not be processed on third-party resources.
This solution is the open-source:

  1. On the server-side: use Gotenberg to convert word & excel files to PDF.
    Note: Gotenberg works like a charm, it is based on the LibreOffice engine.
  2. On the frontend: It's very easy to render the PDF file with javascript. You can use libraries like: pdf.js, react-pdf, etc.)
Masih Jahangiri
  • 6,571
  • 2
  • 35
  • 36
5

ViewerJS is helpful to view/embed openoffice format like odt,odp,ods and also pdf.

For embed openoffice/pdf document

<iframe src = "/ViewerJS/#../demo/ohm2013.odp" width='700' height='550' allowfullscreen webkitallowfullscreen></iframe>

/ViewerJS/ is the path of ViewerJS

#../demo/ohm2013 is the path of your file want to embed

Community
  • 1
  • 1
Naveen DA
  • 3,733
  • 4
  • 37
  • 51
3

I think I have an idea. This has been doing my nut in too and I'm still having trouble getting it to display in Chrome.

Save document(name.docx) in word as single file webpage (name.mht) In your html use

<iframe src= "name.mht" width="100%" height="800"> </iframe>

Alter the heights and widths as you see fit.

Cai Esson
  • 47
  • 1
  • 7
    @guidomocha Don't just comment that, provide reasoning as to why this is a bad approach. – J. Louw Apr 07 '17 at 11:34
  • this approach will display the document text without background graphics, header , footer and other elements.for long files with different elements positioning saving as web page will ruin the design. – sh.e.salh Sep 06 '20 at 03:07
1

If you wanted to pre-process your DOCX files, rather than waiting until runtime you could convert them into HTML first by using a file conversion API such as Zamzar. You could use the API to programatically convert from DOCX to HMTL, save the output to your server and then serve that HTML up to your end users.

Conversion is pretty easy:

curl https://api.zamzar.com/v1/jobs \
-u API_KEY: \
-X POST \
-F "source_file=@my.docx" \
-F "target_format=html5"

This would remove any runtime dependencies on Google & Microsoft's services (for example if they were down, or you were rate limited by them).

It also has the benefit that you could extend to other filetypes if you wanted (PPTX, XLS, DOC etc)

Chris Whyley
  • 442
  • 2
  • 8
1

Native Documents (in which I have an interest) makes a viewer (and editor) specifically for Word documents (both legacy binary .doc and modern docx formats). It does so without lossy conversion to HTML. Here's how to get started https://github.com/NativeDocuments/nd-WordFileEditor/blob/master/README.md

JasonPlutext
  • 14,984
  • 3
  • 43
  • 83
  • 2
    It doesn't have any information on pricing. Is the 'Word File Editor/Viewer' free? – FiringBlanks Feb 18 '19 at 07:00
  • Its commercial software, but we have a free plan for startups/small business, and for others, a free plan subject to usage limits. We'll publish details soon. – JasonPlutext Feb 19 '19 at 07:30
  • can this run on a single page serverless eg on aws s3? – Graham Chiu Apr 06 '19 at 00:57
  • server-side we package it as Docker containers you'd need to run somewhere (eg ECS). (In principle we could run some of this on Lambda, but you'd still want a persistent document store, maybe S3) – JasonPlutext Apr 06 '19 at 21:44
  • 4
    @JasonPlutext This looks interesting. But I'll be blunt: I'm willing to pay a small reasonable fee for a good package or service - but "submit your info and we'll let you know what it costs" is a **NO GO**. – manassehkatz-Moving 2 Codidact Jul 01 '19 at 19:36
1

PDFTron WebViewer supports rendering of Word (and other Office formats) directly in any browser and without any server side dependencies. To test, try https://www.pdftron.com/webviewer/demo

Ika
  • 394
  • 1
  • 14
1

You can also use some existing API's like GroupDocs.Viewer which can convert your document into image or html and then you will be able to display it in your own application.

Dovlet Mamenov
  • 561
  • 6
  • 20
0

Based on some research I got it for IMAGES, PDF, Document and Excel Files preview in Iframe

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>


<script type="text/javascript">
    $(document).ready(function() {
    $('#btnShow').click(function(){
        $("#dialog").dialog({
        height: 600,
        width: 1000,
        show: 'fold',
        modal: true
        });

        var toolbar = "#toolbar=0";

        //pdf
        //$("#frame").attr("src", "pdf_file_url.pdf"+toolbar);
        //image
        //$("#frame").attr("src", "image_file_url.jpeg"+toolbar);

        //document
        $("#frame").attr("src", "https://docs.google.com/gview?embedded=true&url=doc_file_url.docx");

        //excel

      // $("#frame").attr("src", "https://docs.google.com/gview?embedded=true&url=excel_file_url.xlsx");

    }); 
    });
</script>

<a href="javascript:void(0)" id="btnShow">Click to open</a>
<div id="dialog" style="display: none;">
    <div>
    <iframe id="frame" sandbox="allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-presentation allow-same-origin allow-scripts allow-top-navigation allow-top-navigation-by-user-activation" style="height:100%;width:100%;border: 0px;"></iframe>
    </div>
</div>
Ghanshyam Nakiya
  • 1,365
  • 15
  • 22
-2

Use Libre Office API Here is an example

libreoffice --headless --convert-to html docx-file-path --outdir html-dir-path

Salma Elshahawy
  • 1,054
  • 2
  • 11
  • 21