237

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,312
  • 1
  • 16
  • 33
Pankaj
  • 3,131
  • 4
  • 14
  • 22
  • 1
    http://stackoverflow.com/questions/9418850/how-to-display-a-word-document-using-fancybox – Sadikhasan Jan 15 '15 at 06:19
  • 2
    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

14 Answers14

346

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
  • 830
  • 11
  • 33
Brandon Anzaldi
  • 6,884
  • 3
  • 36
  • 55
  • 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
  • 54
    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
  • Couldn't you just leverage the `````` tag to embed the Word file as an OLE object on the page? I've never actually done this myself, but I thought that kind of functionality was why `````` was created in the first place? ‍♀️ – NetXpert Jul 07 '22 at 20:48
  • Is possible to open word file which is saved as base64 string? And how? – devZ Dec 29 '22 at 08:52
46

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
  • 469
  • 4
  • 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
  • 2
    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
  • 1
    @IgorNikiforov for PDFs you can use mozilla's [pdf.js](https://github.com/mozilla/pdf.js/) — it's solid, reliable and time-tested – ccpizza Feb 11 '23 at 20:41
31

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
  • 28,968
  • 18
  • 162
  • 169
  • 3
    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
  • 1
    @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
21

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 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
  • 9,489
  • 3
  • 45
  • 51
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
  • 4,148
  • 4
  • 38
  • 57
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
  • 8
    @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
  • 482
  • 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
  • 15,352
  • 4
  • 44
  • 84
  • 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
  • 402
  • 2
  • 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
  • 581
  • 1
  • 7
  • 20
0
  • There is an android file manager MiXplorer which has features an "HTML Viewer" (ContentViewerActivity) which can display the contents of various docx files pretty well.
  • It works offline, is available for gratis, and setup weighs only ~4 MB (as of latest v6.61.7)
  • It doesn't show exact same thing, rather gives more like a reader view for the files.
  • But since it preserves these:
    • elements: images, tables, lists
    • formatting: font color, & font weight. I guess font size too.
  • I found it suffice for reading most docx files I come across.

I haven't yet found any desktop counterpart.

I am sharing it here in hopes that maybe this can poke someone's interest to figure out how it does that and make is possible on desktop.

If such a light weight html viewer on android can render it (albeit not fully), then it certainly is possible on desktop too, just no current implementation exist.

0

Microsoft users will have a Word Browser within Explorer, however Internet Explorer Office Word Plugin is now way past End of Life. enter image description here

Others have mentioned in answers that for remote files you can use newer 365 MS Web File Viewer as Object Link / Embed such as per click this snippet

<iframe src="https://view.officeapps.live.com/op/embed.aspx?src=https%3A%2F%2Fraw%2Egithubusercontent%2Ecom%3A443%2Fdolanmiu%2Fdocx%2Fmaster%2Fdemo%2Fdotx%2Ftemplate%2Edotx" width="640px" height="300px" frameborder="0">This is an embedded <a target="_blank" href="https://office.com">Microsoft Office</a> document, powered by <a target="_blank" href="https://office.com/webapps">Office</a>.</iframe>
enter image description here

And there are Hybrid WordPad/OpenOffice/Jsview Open Document Template/Text format as a secondary alternative.

However The only way to support the proprietary parts of a DocX are to use an MSOffice Viewer and MS pulled the plug on those too.

Therefor the only really good way to View a complex DocX is once it has been printed as a printout, and the best common format for that is either non searchable image or as searchable SAVE AS PDF

K J
  • 8,045
  • 3
  • 14
  • 36
0

I found this question when looking to render Word and Excel files seamlessly from the web application I was making. The app allows drag and drop uploads attaching files to whatever record displayed on the page. My approach was to create a protocol handler. I chose woi:// for web office interface. Opening a new window having the web address start with that, invokes an exe. It works for all browsers tested. All that's necessary is to register the exe as a protocol handler, which the exe itself does if invoked with no argument as it prompts whether to register or unregister. If the exe exists on the LAN it first copies itself to %userprofile%\AppData\Roaming\web_office_invoker and registers from there.

If the user clicks view on a file, if a PDF it immediately streams to a new window with the response header indicating it's a PDF. Browsers render PDF streams natively. If a Word or Excel file, javascript in the client must first query the application and have the application construct a URL using the woi:// protocol, then open the new window using that URL. The window of course never opens after invoking the exe and passing the entire URL to the exe. Embedded in the URL is a key and other info allowing the exe to make a web request to fetch yet another URL. Finally, Word or Excel are opened with that URL as a command line argument. Word or Excel then makes a request to that URL and the application serves out the unaltered byte stream of the original file that was uploaded. This works perfectly and is totally seamless.

Using Word online is not secure because the document may contain sensitive information, and to use Word online the document would have to be transmitted to Microsoft's server for rendering. This method uses executables installed on the workstation. Also, scripts can be run against Word and Excel documents pulled from the server having replaceable text, to then produce filled out forms.

subjectivist
  • 245
  • 2
  • 12
-2

Use Libre Office API Here is an example

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

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