Insert html in word

I use Visual Basic and an automation interface to retrieve strings from an external application. These strings contain simple html formatting codes (<b>, <i>, etc.).
Is there any easy function in Visual Basic for Word to insert these strings into a word document and convert the html formatting codes to word formatting?

Cindy Meister's user avatar

asked Oct 2, 2008 at 9:36

Here’s a link to add HTML to the clipboard using VB:

http://support.microsoft.com/kb/274326

Once you have the HTML on the clipboard, paste it into your word doc using something like this:

ActiveDocument.Range.PasteSpecial ,,,,WdPasteDataType.wdPasteHTML

This is pretty much the equivalent of you cutting and pasting it in manually.

answered Oct 2, 2008 at 17:18

Jonathan Yee's user avatar

Jonathan YeeJonathan Yee

1,9572 gold badges19 silver badges21 bronze badges

1

Use InsertFile

Set objdoc = objInsp.WordEditor
Set objword = objdoc.Application
Set objsel = objword.Selection
objsel.WholeStory
vs_html = "<html><body>" + vs_body + "</body></html>"
vs_file = "C:temp1.html"
Call DumptoFile(vs_file, "", vs_html, False)
RetVal = objsel.InsertFile(vs_file, , , False, False)

Jonathan Willcock's user avatar

answered Jun 17, 2015 at 13:12

Adz's user avatar

1

I’m using 2016. The only thing that worked was Range.InsertFile(path). Pasting Special didn’t work.

answered Apr 7, 2019 at 1:11

Michael's user avatar

MichaelMichael

1,12715 silver badges15 bronze badges

AFAIK there is no builtin function to do that in VBA. You will have to write it yourself, which would be not too difficult if you restirct it to parse <b>, <i>, <a> and <p>, for example. All other tags would have to be ignored.

answered Oct 2, 2008 at 10:37

Treb's user avatar

TrebTreb

19.8k6 gold badges53 silver badges85 bronze badges

I’d like to embed an online map inside of a Word document for my geography task in school. I have the code for an iframe of a map at www.arcgis.com.

How do I insert it in the document? I’m using Word 2013.

asked Feb 13, 2014 at 16:26

Mikael Dúi Bolinder's user avatar

3

You can copy the HTML code of the iframe to Word but the online map won’t show up as Word can’t display the output of HTML code like a web browser.

answered Feb 13, 2014 at 16:33

Kevin Woblick's user avatar

1

  • Remove From My Forums
  • Question

  • I’m working on a script that reads in an XML Document and pastes the contents into Word in a nicely formatted, readable, presentable format. Or, that’s the idea anyway. Most of it works. One issue I’m having is with tables.

    The tables in the XML source are basically just HTML tables. If I dump the HTML code into an HTML file, then load it in a web browser, it all looks fine. For a simple table, with no merged cells, that’s easy enough to populate into Word as well.

    The issue I’m having is with documents that have tables with merged cells. So it’s not a simple 5×5 table or 3×5 table, etc. The only way I can think of to accommodate this is to parse the HTML code to build the table row by row, and merge cells as I do.
    That is not a prospect I find appealing.

    Is there a way, through PowerShell, to programatically paste the HTML source into the Word document so it recognizes and renders the HTML code? Or is there some other easier way to do this so I don’t have to tear apart each <tr> and <td> element
    to build the table piece by piece?

Answers

    • Marked as answer by

      Thursday, November 9, 2017 6:00 AM

Wordinserter

Build Status image1
image2
image3
image4

This module allows you to insert HTML into a Word Document, as well as
allowing you to programmatically build word documents in pure Python
(Python 3.x only at the moment). After running
pip install wordinserter you can use the wordinserter CLI to
quickly generate test documents:

# Download https://raw.githubusercontent.com/orf/wordinserter/master/tests/docs/table_widths.html
wordinserter table_widths.html --style="table { background-color: red }"

This should open Word and insert three tables, each of them styled with
a red background.

The library is stable and has been used to generate tens of thousands of
reports, and currently supports many features (all controlled through
HTML):

  • Common tags, including tables, lists, code blocks, images,
    hyperlinks, footnotes, headers, paragraphs, styles (b i
    em)
  • Named bookmarks in documents via element id attributes
  • A subset of CSS for elements, with more that can be easily added as
    needed
  • Including document-wide stylesheets while adding elements
  • In-built syntax highlighting for <pre> and <code> blocks
  • Supports complex merged tables, with rowspans and colspans
  • Arbitrarily nested lists of differing types (bullet, numbered, roman
    numerals)
  • Hyperlinks to bookmarks within the document using classic links or
    using Word ‘fields’
  • Images, with support for footnotes, 404 and embedded base64 data-uri
    images
  • Basic whitespace handling

There is a comparison
document
showing the output of WordInserter against Chrome, check it out to see
what the library can do.

API

The API is really simple to use:

from wordinserter import parse, insert

operations = parse(html, parser="html")
insert(operations, document=document, constants=constants)

Inserting HTML into a Word document is a two step process: first the
input has to be parsed into a sequence of operations, which is then
inserted into a Word document. This library currently only supports
inserting using the Word COM interface which means it is Windows
specific at the moment.

Below is a more complex example including starting word that will insert
a representation of the HTML code into the new word document, including
the image, caption and list.

from wordinserter import insert, parse
from comtypes.client import CreateObject

# This opens Microsoft Word and creates a new document.
word = CreateObject("Word.Application")
word.Visible = True # Don't set this to True in production!
document = word.Documents.Add()
from comtypes.gen import Word as constants

html = """
<h3>This is a title</h3>
<p><img src="http://placehold.it/150x150" alt="I go below the image as a caption"></p>
<p><i>This is <b>some</b> text</i> in a <a href="http://google.com">paragraph</a></p>
<ul>
    <li>Boo! I am a <b>list</b></li>
</ul>
"""

# Parse the HTML into a list of operations then feed them into insert.
operations = parse(html, parser="html")
insert(operations, document=document, constants=constants)

What’s with the constants part? Wordinserter is agnostic to the COM
library you use. Each library exposes constant values that are needed by
Wordinserter in a different way: the pywin32 library exposes it as
win32com.client.constants whereas the comtypes library exposes them as a
module that resides in comtypes.gen. Rather than guess which one you are
using Wordinserter requires you to pass the right one in explicitly. If
you need to mix different constant groups you can use the
CombinedConstants class:

from wordinserter.utils import CombinedConstants
from comtypes.gen import Word as word_constants
from comtypes.gen import Office as office_constants

constants = CombinedConstants(word_constants, office_constants)

Install

Get it from PyPi here,
using pip install wordinserter. This has been built with word 2010
and 2013, older versions may produce different results.

Supported Operations

WordInserter currently supports a range of different operations,
including code blocks, font size/colors, images, hyperlinks, numbered
and bullet lists, table borders and padding.

Stylesheets?

Wordinserter has support for stylesheets! Every element can be styled
with inline styles (style='whatever') but this gets tedious at
scale. You can pass CSS stylesheets to the parse function:

html = "<p class="mystyle">Hello Word</p>"
stylesheet = """
.mystyle {
    color: red;
}
"""

operations = parse(html, parser="html", stylesheets=[stylesheet])
insert(operations, document=document, constants=constants)

This will render «Hello Word» in red. Inheritance is respected, so child
styles override parent ones.

Why aren’t my lists showing up properly?

There are two ways people write lists in HTML, one with each sub-list as
a child of the parent list, or as a child of a list element. Below is a
sample of the two different ways, both of which display correctly in all
browsers:

<ol>
    <li>
        I'm a list element
    </li>
    <ul>
        <li>I'm a sub list!</li>
    </ul>
</ol>
<ol>
    <li>
        I'm a list element
        <ul>
            <li>I'm a sub list!</li>
        </ul>
    </li>
</ol>

The second way is correct according to the HTML specification. lxml
parses the first structure incorrectly in some cases, which leads to
weird list behavior. There isn’t much this library can do about that, so
make sure your lists are in the second format.

One other thing to note: Word does not support lists with mixed
list-types on a single level. i.e this HTML will render incorrectly:

<ol>
    <li>
        <ul><li>Unordered List On Level #1</li></ul>
        <ol><li>Ordered List On Level #1</li></ul>
    </li>
</ol>

RRS feed

  • Remove From My Forums
  • Question

  • I want to insert html content in word, I can do it using

    rng.InsertFile(xyx.html)

    where rng is the range where the html content needs to inserted.

    Is there a direct way to insert html content, I will be having the html content from database, to save the html content in a file and then inserting it is not a good way.

    Any Help.

Answers

    • Marked as answer by
      navin agarwal
      Thursday, June 16, 2011 10:08 AM

All replies

    • Marked as answer by
      navin agarwal
      Thursday, June 16, 2011 10:08 AM
  • Thanks Bruce Song for your reply.

    InsertFile is the only option i guess.

    I want to do exactly this in powerpoint presentation, but am not getting any solution.

    Any help on ‘inserting html content in power point presentation’.

    Thanks in advance.

  • Any help on ‘inserting html content in power point presentation’.

    The best place to ask this would be a forum that specializes in PowerPoint. That would be on «Answers»:

    http://answers.microsoft.com/en-us/office/forum/powerpoint?page=1

    But with most Office applications the way to do this would be to put the HTML on the Clipboard then use a Paste method to insert it into the application document. (Word can do it that way, too.)


    Cindy Meister, VSTO/Word MVP

  • Didnt get any answer.

    Is there no other way other than using clipboard using VSTO, using clipboard makes my application slow.

Понравилась статья? Поделить с друзьями:
  • Index number in excel
  • Input field in word
  • Insert header footer in word
  • Index match excel что это
  • Input a word in python