- Convert html to word with images (Using Javascript OR Using jQuery plugin)
- HTML page to Word Doc with images using Javascript
- HTML page to word doc with images using jQuery plugin
- HTML to DOCX converter
- How to convert a HTML to a DOCX file?
- Converter
- Convert to HTML
- Convert from HTML
- File Format
- HTML (Hypertext Markup Language with a client-side image map)
- DOCX (Microsoft Word Open XML Document)
- Конвертировать HTML в DOCX (WORD) / URL в DOCX (WORD) онлайн
- Продвинутый онлайн-сервис конвертации html файлов в DOCX. Для mac & windows
- Язык гипертекстовой разметки
- Microsoft Office Open XML
- HTML to DOCX Converter
- convert to
- compress
- capture website as
- create archive
- extract
- Options
- HTML
- DOCX
- +200 Formats Supported
- Data Security
- High-Quality Conversions
- Powerful API
Convert html to word with images (Using Javascript OR Using jQuery plugin)
In this article, we will be exporting HTML to Word doc file with images using jQuery plugin or without using any plugin, with pure javascript. Although there are many plugin available on internet which converts html page into word document but we will be using jquery.wordexport.js which also requires filesaver.js to save files on client browser, using HTML 5 Localstorage.
HTML page to Word Doc with images using Javascript
In the method, we will not be using any jquery plugin, we will be converting complete HTML with image into doc using javascript code.
1. Create the javascript function to export to doc
function ExportToDoc(filename = '')< var HtmlHead = ""; var EndHtml = ""; //complete html var html = HtmlHead +document.getElementById("MainHTML").innerHTML+EndHtml; //specify the type var blob = new Blob(['\ufeff', html], < type: 'application/msword' >); // Specify link url var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html); // Specify file name filename = filename?filename+'.doc':'document.doc'; // Create download link element var downloadLink = document.createElement("a"); document.body.appendChild(downloadLink); if(navigator.msSaveOrOpenBlob )< navigator.msSaveOrOpenBlob(blob, filename); >else < // Create a link to the file downloadLink.href = url; // Setting the file name downloadLink.download = filename; //triggering the function downloadLink.click(); >document.body.removeChild(downloadLink); >
In the above code, we are getting contents of element with id «MainHTML» and then converting it into blob of type MSWord. You can also modify code to pass element dynamically by adding an argument in «ExportToDoc» function and then passing that element’s html.
2. Let’s create the HTML which we will export
Centered HTML H1 Heading Heading 2
Some text inside paragraph.
Export to Doc
See the Pen ExjxwZv by Vikas Lalwani (@vikas-lalwani) on CodePen.
HTML page to word doc with images using jQuery plugin
Let’s create a simple HTML page with image, which we will be using to convert to MS word Document.
Centered HTML H1 Heading Heading 2
Some text inside paragraph.
Export to Doc
In the above code, we have simply added few headings and a image file in base64 format.
Now, let’s add the required plugins, which is filesaver.js, jquery.js
I have not added link to jQuery.wordexport.js, as we will be using direct plugin code because it is not available on cdn as of now, and here the complete function code
// jQuery html to word plugin function if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") < (function($) < $.fn.wordExport = function(fileName) < fileName = typeof fileName !== 'undefined' ? fileName : "jQuery-Word-Export"; var static = < mhtml: < top: "Mime-Version: 1.0\nContent-Base: " + location.href + "\nContent-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset=\"utf-8\"\nContent-Location: " + location.href + "\n\n\n\n_html_", head: "\n\n\n\n", body: "_body_" > >; var options = < maxWidth: 624 >; // Clone selected element before manipulating it var markup = $(this).clone(); // Remove hidden elements from the output markup.each(function() < var self = $(this); if (self.is(':hidden')) self.remove(); >); // Embed all images using Data URLs var images = Array(); var img = markup.find('img'); for (var i = 0; i < img.length; i++) < // Calculate dimensions of output image var w = Math.min(img[i].width, options.maxWidth); var h = img[i].height * (w / img[i].width); // Create canvas for converting image to data URL var canvas = document.createElement("CANVAS"); canvas.width = w; canvas.height = h; // Draw image to canvas var context = canvas.getContext('2d'); context.drawImage(img[i], 0, 0, w, h); // Get data URL encoding of image var uri = canvas.toDataURL("image/png"); $(img[i]).attr("src", img[i].src); img[i].width = w; img[i].height = h; // Save encoded image to array images[i] = < type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")), encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")), location: $(img[i]).attr("src"), data: uri.substring(uri.indexOf(",") + 1) >; > // Prepare bottom of mhtml file with image data var mhtmlBottom = "\n"; for (var i = 0; i < images.length; i++) < mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n"; mhtmlBottom += "Content-Location: " + images[i].location + "\n"; mhtmlBottom += "Content-Type: " + images[i].type + "\n"; mhtmlBottom += "Content-Transfer-Encoding: " + images[i].encoding + "\n\n"; mhtmlBottom += images[i].data + "\n\n"; >mhtmlBottom += "--NEXT.ITEM-BOUNDARY--"; //TODO: load css from included stylesheet var styles = ""; // Aggregate parts of the file together var fileContent = static.mhtml.top.replace("_html_", static.mhtml.head.replace("_styles_", styles) + static.mhtml.body.replace("_body_", markup.html())) + mhtmlBottom; // Create a Blob with the file contents var blob = new Blob([fileContent], < type: "application/msword;charset=utf-8" >); saveAs(blob, fileName + ".doc"); >; >)(jQuery); > else < if (typeof jQuery === "undefined") < console.error("jQuery Word Export: missing dependency (jQuery)"); >if (typeof saveAs === "undefined") < console.error("jQuery Word Export: missing dependency (FileSaver.js)"); >>
Now, add the jQuery code to call the above function on click and convert html to doc
jQuery(document).ready(function($) < $("a.word-export").click(function(event) < $("#MainHTML").wordExport(); >); >);
That’s, it, we are ready, here is the Codepen sample
See the Pen XWbWeaa by Vikas Lalwani (@vikas-lalwani) on CodePen.
Output is same as above, but in this approach we are using jQuery plugin and also converting image into base64 to get it work.
HTML to DOCX converter
This online document converter allows you to convert your files from HTML to DOCX in high quality.
We support a lot of different file formats like PDF, DOCX, PPTX, XLSX and many more. By using the online-convert.com conversion technology, you will get very accurate conversion results.
How to convert a HTML to a DOCX file?
- Choose the HTML file you want to convert
- Change quality or size (optional)
- Click on «Start conversion» to convert your file from HTML to DOCX
- Download your DOCX file
To convert in the opposite direction, click here to convert from DOCX to HTML:
Not convinced? Click on the following link to convert our demo file from HTML to DOCX:
Rate this tool 3.2 / 5
You need to convert and download at least 1 file to provide feedback
Converter
Convert to HTML
Convert from HTML
File Format
HTML (Hypertext Markup Language with a client-side image map)
HTML (HyperText Markup Language) is the standard for creating websites. The idea was proposed in 1989 by physicist Tim Berners-Lee at CERN. Web browsers can read this language to interpret the coding into different texts, colors, formats (headings, p.
DOCX (Microsoft Word Open XML Document)
DOCX is an advanced version of the DOC file format and is much more usable and accessible than the latter at any given time. Unlike the DOC file, the DOCX file is not an extensive file format. Instead, it appears as being a single file while actuall.
Конвертировать HTML в DOCX (WORD) / URL в DOCX (WORD) онлайн
Продвинутый онлайн-сервис конвертации html файлов в DOCX. Для mac & windows
- Image
- Document
- Ebook
- Audio
- Archive
- Video
- Presentation
- Font
- Vector
- CAD
- Image
- Document
- Ebook
- Audio
- Archive
- Video
- Presentation
- Font
- Vector
- CAD
Язык гипертекстовой разметки
HTML ― это файл веб-формата. Исходный код HTML можно изменить в текстовом редакторе. HTML-файлы разрабатываются для будущего использования в веб-браузерах пользователей и позволяют форматировать сайты с текстом, изображениями и другими необходимыми материалами. В файлах этого формата используются теги для создания веб-страниц. Интерпретация HTML-кода выполняется веб-браузером, и этот код, как правило, не показывается пользователю.
Microsoft Office Open XML
С 2007 года Microsoft начал использовать формат файла docx, созданный с использованием формата Office Open XML. Этот формат представляет собой сжатый файл, содержащий текст в форме XML, графики и иные данные, которые могут быть преобразованы в битовые последовательность при помощи защищенных патентами двоичных форматов. Поначалу предполагалось, что этот формат заменит формат doc, но оба формата все еще используются по сегодняшний день.
HTML to DOCX Converter
CloudConvert is an online document converter. Amongst many others, we support PDF, DOCX, PPTX, XLSX. Thanks to our advanced conversion technology the quality of the output will be as good as if the file was saved through the latest Microsoft Office 2021 suite.
convert to
compress
capture website as
create archive
extract
Options
HTML
HTML is a markup language that is used to create web pages. Web browsers can parse the HTML file. This file format use tags (e.g ) to build web contents. It can embed texts, image, heading, tables etc using the tags. Other markup languages like PHP, CSS etc can be used with html tags.
DOCX
DOCX is an XML based word processing file developed by Microsoft. DOCX files are different than DOC files as DOCX files store data in separate compressed files and folders. Earlier versions of Microsoft Office (earlier than Office 2007) do not support DOCX files because DOCX is XML based where the earlier versions save DOC file as a single binary file.
+200 Formats Supported
CloudConvert is your universal app for file conversions. We support nearly all audio, video, document, ebook, archive, image, spreadsheet, and presentation formats. Plus, you can use our online tool without downloading any software.
Data Security
CloudConvert has been trusted by our users and customers since its founding in 2012. No one except you will ever have access to your files. We earn money by selling access to our API, not by selling your data. Read more about that in our Privacy Policy.
High-Quality Conversions
Besides using open source software under the hood, we’ve partnered with various software vendors to provide the best possible results. Most conversion types can be adjusted to your needs such as setting the quality and many other options.
Powerful API
Our API allows custom integrations with your app. You pay only for what you actually use, and there are huge discounts for high-volume customers. We provide a lot of handy features such as full Amazon S3 integration. Check out the CloudConvert API.