Word editor in html

About

A handy tool to edit, import, and view word documents. Simply open an .html file via the File menu (File > Open file). Please note that this app has a JavaScript word compiler (TinyMCE) that can compile HTML documents to word and vice versa. Once the word document is rendered, you can save it as a .html format or print it as a .pdf file.

Description

This web application is designed to render word documents as HTML5. For compiling word documents, it uses TinyMCE javascript API. With this web application, you can import, edit and view word documents to HTML5. For complex documents, please use a native word application based on your operating system.

The top toolbar has several menu buttons. These buttons are similar to a common word processor software and most of them are self-explanatory. To open a document you can use the File menu or drag and drop your file in the app interface. Please note that the acceptable file extension is (.html). On the top right corner, there is a dark mode button to change the app theme to the dark style. This word application uses TinyMCE JavaScript API to compile and render word documents. You can get more info about this API in this GitHub repo. Please note that once the app loads completely you can use it offline and without any internet connection. Moreover, to save a file to disk, this app uses the default download location on your machine. Therefore to change the location please head to your browser’s settings tab and update the download location to your desired one.

Note: word editor app is suitable for editing lightweight word documents. If you have a heavy document with plenty of graphics, please use a native word processor application. HTML5 base word editors are mostly suitable for editing simple documents on mobile or desktop browsers. Due to limitations in JavaScript language, these editors are not very efficient in handling large data with high CPU or RAM footprints.

Word Editor app is also available as a browser extension. As an extension, this app does not need an internet connection and can be used offline in your browser. Download links for three popular browsers are as follows: Chrome, Edge, Opera, Firefox.

If you found a bug in this page, or have a feature/function which you would like to see in this web app, please let us know by sending an email or through the discussion form below. Moreover, don’t forget to check other web apps in webbrowsertools.com, we have many useful apps related to browser’s privacy and security.

Related Blog Posts

  1. Why a Website or Service Cannot be Accessed: It is always possible for even some of the most prominent websites or services to go down. Although the downtime of websites such as Twitter, YouTube or Face is often measured in seconds, other websites, on the other hand, might be down for hours or in some cases, days at a time…
  2. Clear Browser Cache: Just about everyone wants to know how to clear browser cache for their browser (Chrome, Firefox and Opera). It is an important diagnostic after all when one is having issues with the website loading or privacy…

docx-html-editor

A proof of concept (JAX-RS 2.0) to show how a web-based HTML rich text editors (eg CkEditor) can be
used to edit docx files (via XHTML round trip).

We’ve published this as a «cheap and cheerful» option only; for a commercial grade solution (new in 2018), please see
https://nativedocuments.com/ (which takes a completely different approach).

That said, it should work OK for documents containing text, tables, and images.
Exotic Word features are not supported.

Interested docx4j community members are welcome to improve it and offer pull requests.

docx-html-editor is licensed under the AGPLv3. This means you have to publish any changes you make.

How it works

The idea is:

  • use docx4j to convert the docx to XHTML
  • use CKEditor to edit that XHTML in the web browser
  • on submit, convert the XHTML back to docx content

The general problem with converting to/from XHTML is the “impendance mismatch”. That is, losing stuff during round trip. This will be a familiar problem to anyone who has ever edited a docx in Google Docs or LibreOffice.

This demo addresses that problem by identifying docx content which CKEditor would mangle, and then on submit/save, using the original docx content for those bits.

In this demo, the problematic content is replaced with visual placeholders, so you can see it is there.

Getting started

Pre-reqs: Since we don’t distribute a binary, you’ll need maven to build from source.

Get CKeditor (v3.6.6.1); unzip it to src/main/webapp/ckeditor
(so you have src/main/webapp/ckeditor/ckeditor.js etc)

Build the war:

Load the resulting war file from dir target to your app server (eg Tomcat)

Visit the upload page in your web browser

There’s a bit more doco at https://github.com/plutext/docx-html-editor/blob/master/documentation/user/docx-html-editor_UserManual.docx?raw=true

Developing

Set this up as a Maven project (eg in Eclipse) to get the dependencies.

Если добавить атрибут contenteditable к элементу, его содержимое становится доступно для редактирования пользователю, а с использованием JS и JQuery можно сделать простой WYSIWYG редактор.

<div class="editor" contenteditable="true"></div>

HTML

1

ExecCommand

JS-метод document.execCommand(сommand, showDefaultUI, аrgument) применяет команды к элементу с атрибутом contenteditable, который находится в фокусе. Т.к. нет единого стандарта, логика команд может отличатся в разных браузерах так и их поддержка, описание команд на https://developer.mozilla.org.

Проверить доступность команды можно методом queryCommandSupported(сommand).

var enable = document.queryCommandSupported('paste');
if (enable) {
	...
}

JS

Поддержка команд в браузере:

Жирный

Включает и отключает у выделенного текста жирное начертание тегом <b>, IE использует тег <strong>.

document.execCommand('bold', false, null);

JS

Курсив

Тег <i>, IE использует <em>.

document.execCommand('italic', false, null);

JS

Подчеркнутый

Тег <u>.

document.execCommand('underline', false, null);

JS

Перечёркнутый

Тег <strike>.

document.execCommand('strikethrough', false, null);

JS

Верхний индекс

Тег <sup>.

document.execCommand('superscript', false, null);

JS

Нижний индекс

Тег <sub>.

document.execCommand('subscript', false, null);

JS

Маркированный список

Тег <ul>.

document.execCommand('insertUnorderedList', false, null);

JS

Нумерованный список

Тег <ol>.

document.execCommand('insertOrderedList', false, null);

JS

Заголовки, параграф, цитата и т.д.

formatBlock добавляет блочный тег вокруг выделенного текста.

document.execCommand('formatBlock', false, 'h1');
document.execCommand('formatBlock', false, 'h2');
document.execCommand('formatBlock', false, 'h3');
document.execCommand('formatBlock', false, 'p');
document.execCommand('formatBlock', false, 'blockquote');
document.execCommand('formatBlock', false, 'div');

JS

Горизонтальная линия

Тег <hr>.

document.execCommand('insertHorizontalRule', false, null);

JS

Изображение

var url = prompt('Введите адрес изображения', '');
document.execCommand('insertImage', false, url);

JS

Ссылка

var url = prompt('Введите URL', '');
document.execCommand('CreateLink', false, url);

JS

Удаление ссылки:

document.execCommand('unlink', false, null);

JS

Вставка текста

var text = prompt('Введите текст', '');
document.execCommand('insertText', false, text);

JS

Вставка HTML

var html = prompt('Введите HTML код', '');
document.execCommand('insertHTML', false, html);

JS

С помощью insertHTML можно обернурнуть выделенный текст тегом, например <pre>:

document.execCommand('insertHTML', false, '<pre>' + document.getSelection().toString() + '</pre>');

JS

Выравнивание текста

Добавляет родительскому блоку CSS-свойство text-align.

По левому краю:

document.execCommand('justifyLeft', false, null);

JS

По центру:

document.execCommand('justifyCenter', false, null);

JS

По правому краю:

document.execCommand('justifyRight', false, null);

JS

По ширине:

document.execCommand('justifyFull', false, null);

JS

Шрифты

По умолчанию команды установки шрифта добавляются тегом <font> c атрибутами face, size, color, что не очень хорошо.

Команда styleWithCSS переключает режим, в место семантических тегов добавляются <span style="...">.

После установки шрифта нужно переключить styleWithCSS обратно т.к. он распространяется на другие теги (<b>, <i>, <s> и т.д.).

Название шрифта

document.execCommand('styleWithCSS', false, true);
document.execCommand('fontName', false, 'monospace');
document.execCommand('styleWithCSS', false, false);

JS

Размер:

Размер шрифта задаётся в условных единицах (1-7), в режиме styleWithCSS некоторые браузеры используют font-size: xx-small, x-small, small, medium, large, x-large, xx-large.

document.execCommand('styleWithCSS', false, true);
document.execCommand('fontSize', false, '5');
document.execCommand('styleWithCSS', false, false);

JS

Цвет:

document.execCommand('styleWithCSS', false, true);
document.execCommand('foreColor', false, '#eeeeee');
document.execCommand('styleWithCSS', false, false);

JS

Фон:

document.execCommand('styleWithCSS', false, true);
document.execCommand('hiliteColor', false, 'orange');
document.execCommand('styleWithCSS', false, false);

JS

Undo и Redo

Отмена последнего действия, Ctrl + z.

document.execCommand('undo', false, null);

JS

Повтор последнего действия, Ctrl + y.

document.execCommand('redo', false, null);

JS

Выделить всё

document.execCommand('selectAll', false, null);

JS

Удаление выделенного

document.execCommand('delete', false, null);

JS

Очистить стили

Удаляет инлайновые теги и атрибуты style, все блочные теги остаются.

document.execCommand('removeFormat', false, null);

JS

Вырезать

document.execCommand('cut', false, null);

JS

Копировать

document.execCommand('copy', false, null);

JS

2

Пример редактора

  • HTML
  • CSS
  • JS
<link href="/font-awesome.min.css" rel="stylesheet">
<script src="/jquery.min.js"></script>

<div class="toolbar">
	<a href="#" class="toolbar-b fas fa-bold" title="Жирный"></a>
	<a href="#" class="toolbar-i fas fa-italic" title="Курсив"></a>
	<a href="#" class="toolbar-u fas fa-underline" title="Подчёркнутый"></a>
	<a href="#" class="toolbar-s fas fa-strikethrough" title="Зачёркнутый"></a>
	<a href="#" class="toolbar-sup fas fa-superscript" title="Верхний индекс"></a>
	<a href="#" class="toolbar-sub fas fa-subscript" title="Нижний индекс"></a>
	<a href="#" class="toolbar-ul fas fa-list-ul" title="Маркированный список"></a>
	<a href="#" class="toolbar-ol fas fa-list-ol" title="Нумерованный список"></a>
	<a href="#" class="toolbar-p" title="Параграф">p</a>  
	<a href="#" class="toolbar-h1" title="Заголовок">H1</a>
	<a href="#" class="toolbar-hr" title="Горизонтальная линия">hr</a>    
	<a href="#" class="toolbar-blockquote fas fa-quote-right" title="Цитата"></a>
	<a href="#" class="toolbar-img far fa-image" title="Изображение"></a>
 	<a href="#" class="toolbar-a fas fa-link" title="Ссылка"></a>  
	<a href="#" class="toolbar-unlink fas fa-unlink" title="Удаление ссылки"></a>
	<a href="#" class="toolbar-html" title="Вставить html">HTML</a>  
	<a href="#" class="toolbar-text" title="Вставить текст">Text</a>
	<br>	
	<a href="#" class="toolbar-left fas fa-align-left" title="по левому краю"></a>
	<a href="#" class="toolbar-center fas fa-align-center" title="по центру"></a>
	<a href="#" class="toolbar-right fas fa-align-right" title="по правому краю"></a>
	<a href="#" class="toolbar-justify fas fa-align-justify" title="по ширине"></a>
	<select class="toolbar-font">
		<option selected="selected" disabled="disabled">Шрифт</option>
		<option value="arial">Arial</option>
		<option value="Courier New">Courier New</option>
		<option value="georgia">Georgia</option>
		<option value="impact">Impact</option>
		<option value="roboto">Tahoma</option>
		<option value="Times New Roman">Times New Roman</option>
		<option value="verdana">Verdana</option>
	</select>
	<select class="toolbar-size">
		<option selected="selected" disabled="disabled">Размер</option>
		<option value="1">10px</option>
		<option value="2">12px</option>
		<option value="3">14px</option>
		<option value="4">16px</option>
		<option value="5">18px</option>
		<option value="6">21px</option>
		<option value="7">26px</option>
	</select>
	<span>Цвет</span> <input class="toolbar-color" type="color" value="#ff0000">
	<span>Фон</span> <input class="toolbar-bg" type="color" value="#ffff00">
	<br>
	<a href="#" class="toolbar-undo fas fa-undo" title="Отмена"></a>
	<a href="#" class="toolbar-redo fas fa-redo" title="Повтор"></a>  		
	<a href="#" class="toolbar-delete far fa-trash-alt" title="Удалить"></a>
	<a href="#" class="toolbar-selectAll">Выделить всё</a>
	<a href="#" class="toolbar-removeFormat">Очистить стили</a>
	<a href="#" class="toolbar-cut fas fa-cut" title="Вырезать"></a>
	<a href="#" class="toolbar-copy fas fa-copy" title="Копировать"></a>
</div>

<div class="editor" contenteditable="true">...</div>

HTML

.toolbar a {
	display: inline-block;
	border: 1px solid #888;
	padding: 5px 8px;
	margin: 0 5px 10px 0;
	color: #000;
	border-radius: 3px;
	font-size: 12px;
	box-shadow: 1px 1px 2px #ddd;
	background: #fff;
	vertical-align: top;
	text-decoration: none;
}
.toolbar select {
	display: inline-block;
	height: 28px;
	line-height: 28px;
	background: #fff;
	padding: 0;
	margin: 0 5px 10px 0;
	color: #000;
	box-shadow: 1px 1px 2px #ddd;
	border-radius: 3px;
	vertical-align: top;
  	font-size: 12px;
}
.toolbar input {
	display: inline-block;
	height: 28px;
	line-height: 28px;
	background: #fff;
	padding: 0;
	margin: 0 5px 10px 0;
	color: #000;
	box-shadow: 1px 1px 2px #ddd;
	border-radius: 3px;
	vertical-align: top;
	font-size: 12px;
}
.toolbar span {
	display: inline-block;
	height: 30px;
	line-height: 30px;
	padding: 0;
	margin: 0 0 10px 0;
	color: #000;
	vertical-align: top;
	font-size: 12px;
}
.editor {
	min-height: 150px;
	border: 1px solid #ddd;
	padding: 10px;
	border-radius: 2px;
	box-shadow: 1px 1px 2px #ddd;
	background: #fff;
}

CSS

// Жирный (b)
$('body').on('click', '.toolbar-b', function(){
	document.execCommand('bold', false, null);
	return false;
});

// Курсив (i)
$('body').on('click', '.toolbar-i', function(){
	document.execCommand('italic', false, null);
	return false;
});

// Подчёркнутый текст (u)
$('body').on('click', '.toolbar-u', function(){
	document.execCommand('underline', false, null);
	return false;
});

// Зачёркнутый текст (strike)
$('body').on('click', '.toolbar-s', function(){
	document.execCommand('strikethrough', false, null);
	return false;
});

// Верхний индекс (sup)
$('body').on('click', '.toolbar-sup', function(){
	document.execCommand('superscript', false, null);
	return false;
});

// Нижний индекс (sub)
$('body').on('click', '.toolbar-sub', function(){
	document.execCommand('subscript', false, null);
	return false;
});

// Маркированный список (ul)
$('body').on('click', '.toolbar-ul', function(){
	document.execCommand('insertUnorderedList', false, null);
	return false;
});

// Нумерованный список (ol)
$('body').on('click', '.toolbar-ol', function(){
	document.execCommand('insertOrderedList', false, null);
	return false;
});

// Параграф (p)
$('body').on('click', '.toolbar-p', function(){
	document.execCommand('formatBlock', false, 'p');
	return false;
});

// Заголовок (h1)
$('body').on('click', '.toolbar-h1', function(){
	document.execCommand('formatBlock', false, 'h1');
	return false;
});

// Горизонтальная линия (hr) 
$('body').on('click', '.toolbar-hr', function(){
	document.execCommand('insertHorizontalRule', false, null);
	return false;
});

// Цитата (blockquote)
$('body').on('click', '.toolbar-blockquote', function(){
	document.execCommand('formatBlock', false, 'blockquote');
	return false;
});	

// Изображение (img)
$('body').on('click', '.toolbar-img', function(){
	var url = prompt('Введите адрес изображения', 'https://snipp.ru/demo/526/image.jpg');
	document.execCommand('insertImage', false, url);
	return false;
});

// Ссылка (a)
$('body').on('click', '.toolbar-a', function(){
	var url = prompt('Введите URL', '');
	document.execCommand('CreateLink', false, url);
	return false;
});

// Удаление ссылки
$('body').on('click', '.toolbar-unlink', function(){
	document.execCommand('unlink', false, null);
	return false;
});

// Вставить html
$('body').on('click', '.toolbar-html', function(){
	var html = prompt('Введите HTML код', '');
	document.execCommand('insertHTML', false, html);
	return false;
});

// Вставить текст
$('body').on('click', '.toolbar-text', function(){
	var text = prompt('Введите текст', '');
	document.execCommand('insertText', false, text);
	return false;
});

// Выравнивание текста по левому краю
$('body').on('click', '.toolbar-left', function(){
	document.execCommand('justifyLeft', false, null);
	return false;
});

// Выравнивание текста по центру
$('body').on('click', '.toolbar-center', function(){
	document.execCommand('justifyCenter', false, null);
	return false;
});

// Выравнивание текста по правому краю
$('body').on('click', '.toolbar-right', function(){
	document.execCommand('justifyRight', false, null);
	return false;
});

// Выравнивание по ширине
$('body').on('click', '.toolbar-justify', function(){
	document.execCommand('justifyFull', false, null);
	return false;
});

// Шрифт
$('body').on('input', '.toolbar-font', function(){
	var val = $(this).val();
	document.execCommand('styleWithCSS', false, true);
	document.execCommand('fontName', false, val);
	document.execCommand('styleWithCSS', false, false);
});

// Размер шрифта
$('body').on('input', '.toolbar-size', function(){
	var val = $(this).val();
	document.execCommand('styleWithCSS', false, true);
	document.execCommand('fontSize', false, val);
	document.execCommand('styleWithCSS', false, false);
});

// Цвет шрифта
$('body').on('input', '.toolbar-color', function(){
	var val = $(this).val();
	document.execCommand('styleWithCSS', false, true);
	document.execCommand('foreColor', false, val);
	document.execCommand('styleWithCSS', false, false);
});

// Цвет фона
$('body').on('input', '.toolbar-bg', function(){
	var val = $(this).val();
	document.execCommand('styleWithCSS', false, true);
	document.execCommand('hiliteColor', false, val);
	document.execCommand('styleWithCSS', false, false);
});

// Отмена
$('body').on('click', '.toolbar-undo', function(){
	document.execCommand('undo', false, null);
	return false;
});

// Повтор
$('body').on('click', '.toolbar-redo', function(){
	document.execCommand('redo', false, null);
	return false;
});

// Удалить
$('body').on('click', '.toolbar-delete', function(){
	document.execCommand('delete', false, null);
	return false;
});

// Выделить всё
$('body').on('click', '.toolbar-selectAll', function(){
	document.execCommand('selectAll', false, null);
	return false;
});

// Очистить стили
$('body').on('click', '.toolbar-removeFormat', function(){
	document.execCommand('removeFormat', false, null);
	return false;
});

// Вырезать
$('body').on('click', '.toolbar-cut', function(){
	document.execCommand('cut', false, null);
	return false;
});

// Копировать
$('body').on('click', '.toolbar-copy', function(){
	document.execCommand('copy', false, null);
	return false;
});

JS

3

Переносы строк

В большинстве браузерах при нажатии на Enter, новая строка начнется с преведущего блочного элемента (p, li, blockquote).

Если редактор был пуст, то вставится <div>, в место него можно использовать <p> вызвав команду:

document.execCommand('defaultParagraphSeparator', false, 'p');

JS

Если редактору сделать display: inline-block, то будут вставляться только <br>.

4

Табуляция

В contenteditable клавиша Tab не добавляет отступ, а переключает фокус на следующий элемент. Включить табуляцию можно, добавив CSS-свойство white-space: pre-wrap чтобы начали выводится пробельные символы, но при этом переносы строк тоже заработают.

.editor {
	white-space: pre-wrap;
	tab-size: 3; /* Ширина табуляции */
}

CSS

И обработчик нажатия клавиши на JQuery:

$('body').on('keydown', '.editor', function(e){
	if (e.keyCode === 9) { 
		e.preventDefault();
		var editor = this;
		var doc = editor.ownerDocument.defaultView;
		var sel = doc.getSelection();
		var range = sel.getRangeAt(0);
		var tabNode = document.createTextNode("t");
		range.insertNode(tabNode);
		range.setStartAfter(tabNode);
		range.setEndAfter(tabNode); 
		sel.removeAllRanges();
		sel.addRange(range);
	}		
});

JS

Результат:

5

Удаление стилей при вставке

При вставки текста из буфера переносятся все стили и теги скопированные из HTML страницы или Word файла, это можно предотвратить очисткой:

function escape_text(text) { 
	var map = {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '''};
	return text.replace(/[&<>"']/g, function(m) {
		return map[m];
	});
}

$('body').on('paste', '.editor', function(e){
	e.preventDefault();
	var text = (e.originalEvent || e).clipboardData.getData('text/plain');
	document.execCommand('insertHtml', false, escape_text(text));
});

JS

6

Placeholder в contenteditable

<div class="editor" contenteditable="true" placeholder="Введите текст"></div>

HTML

.editor[placeholder]:empty:before {
	content: attr(placeholder);
	color: #555; 
}
.editor[placeholder]:empty:focus:before {
	content: '';
}

CSS

$('body').on('focusout', '.editor', function() {
	var element = $(this);        
	if (!element.text().replace(' ', '').length) {
		element.empty();
	}
});

JS

7

Показать/скрыть исходный код

Показать исходный код можно заменив <div> на <textarea>.

<input type="checkbox" id="toggle-editor"> Показать исходный код

<div contenteditable="true" class="editor">
	...
</div>

HTML

textarea.editor {
	display: block;
	width: 100%;
	box-sizing: border-box;
	white-space: pre-wrap;
}

CSS

$('#toggle-editor').click(function(){
	var target = $('.editor');
	if ($(this).is(':checked')){
		target.replaceWith('<textarea class="editor">' + target.html() + '</textarea>');
	} else {
		target.replaceWith('<div contenteditable="true" class="editor">' + target.val() + '</div>');
	}
});

JS

8

Отправка с формой

Для отправки текста вместе с формой нужно добавить скрытый <textarea>, при событии отправки формы скидывать в него содержимое редактора.

<form id="form" method="post" action="">
	<div class="editor" contenteditable="true">...</div>
	<textarea id="textarea" name="text" style="dispalay: none;"></textarea>
	<input type="supmit" value="Отправить">
</form>

HTML

$('#form').on('submit', function(){
	$('#textarea').val($('.editor').html());
	return true;
});

JS

Writing a blog post and want to share a DOCX with a wider audience? Fortunately, you can embed office files on your website, including Word documents. Learn how in this article.
How to embed Word document in HTML?

To embed DOCX in HTML is a perfect way of motivating users to interact with the file right on a webpage. It improves engagement and people don’t need to download a Word document for reading.

All website creating platforms support HTML whether you’re using HTML4 or HTML5. In this post, we’ll go through embedding DOCX files on WordPress.

Integrate WordPress with ONLYOFFICE Docs

With the recently added ONLYOFFICE add-on for WP, you can easily embed uploaded DOCX files just as any other content. To install it, you need to have WordPress 5.7 or newer version. Here are the steps:

  1. After logging in to your admin profile, hover on Plugins and click on Add New.
  2. Using the search bar, find ONLYOFFICE.
  3. Install and activate the plugin.

Now proceed to the article where you want to insert a text document.

Note: To enable the integration, you need to install ONLYOFFICE Docs and configure the plugin.

Embed a Word document as a block

In 2019, WordPress introduced a block editor Gutenberg, which replaced the classic visual editor and made article drafting faster and easier even for beginners.

Open your article and add a new block.

Choose ONLYOFFICE and upload a DOCX file.

Finally, preview the page to see the result and publish the article. Easy!

What else is good to know about embedding DOCX in HTML?

Here are some additional questions around DOCX embedding that could help you along the way.

Can visitors edit embedded Word files?

No. Documents will be opened in the article for viewing. While people can read the content, it remains non-editable for anyone but you.

Are there other benefits of ONLYOFFICE for WordPress?

Embedding is not the only action ONLYOFFICE can perform on WordPress. Additionally, you’re able to edit office files (Word documents, Excel spreadsheets, PowerPoint presentations) right from the admin dashboard.

Besides, there’s a plugin for ONLYOFFICE editors, which allows direct publishing articles to your site.

How to embed a Word file using HTML coding?

If you’re using ONLYOFFICE Workspace, you can easily generate an embedding code for a particular file:

  1. Open your Documents module and find the desired file.
  2. Click on Share → Add link.
  3. Press External link and select Embedding settings from the drop-down list.
  4. Adjust the settings, if needed. Then copypaste the code to your WP editor.

This way is a bit more complicated for beginners, but allows customization of the embedded window.

Why not just create a hyperlink to my DOCX file?

Hyperlinks are good to navigate people on the site, but only if you don’t have too many. There are other reasons to avoid them while distributing DOCX files, though.

  • To open a text document in a new tab, you’ll need to store it somewhere and then create a link. When you delete this doc or change its path, the link in the blog post will become invalid as well. And monitoring each link is another pretty time-consuming task.
  • The second scenario is a hyperlink to a direct download of a Word document. New visitors and digital security geeks who are always aware of everything that gets downloaded on their machines may think you’re distributing malicious content.

In contrast, embedded Word documents are stored on WordPress (or other CMS) and visitors have immediate access to the content without downloading files.

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

Понравилась статья? Поделить с друзьями:
  • Word dress in russian
  • Word drawing a straight line
  • Word draw on image
  • Word drag and drop text
  • Word download windows 10 torrent