MsOffi...Writer(3pm)

πŸ“¦
version 1.10 Β· 3 versions
, in debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– MsOffice::Word::HTML::Writer πŸ’–

okay bestie, gather round β€” this is the manual page for MsOffice::Word::HTML::Writer (that's the MsOffi...Writer(3pm) situation, the terminal just refuses to show the whole name because it has main character energy and a very long name, iykyk). It lives in the User Contributed Perl Documentation section and it is long, so buckle up.


✨ NAME ✨

MsOffice::Word::HTML::Writer β€” writing documents for MsWord in HTML format. πŸ’…


🌸 SYNOPSIS 🌸

use MsOffice::Word::HTML::Writer;
my $doc = MsOffice::Word::HTML::Writer->new(
  title        => "My new doc",
  WordDocument => {View => 'Print'},
  charset      => "windows-1252",    # optional -- the default charset is utf-8
);

$doc->write("<p>hello, world</p>",
            $doc->page_break,
            "<p>hello from another page</p>");

$doc->create_section(
  page => {size         => "21.0cm 29.7cm",
           margin       => "1.2cm 2.4cm 2.3cm 2.4cm",
           page_numbers => 50, # initial page number within this section
          },
  header => sprintf("Section 2, page %s of %s",
                                $doc->field('PAGE'),
                                $doc->field('NUMPAGES')),
  footer => sprintf("printed at %s",
                                $doc->field('PRINTDATE')),
  new_page => 1, # or 'always', or 'left', or 'right'
);
$doc->write("this is the second section, look at header/footer");

$doc->attach("my_image.gif", $path_to_my_image);
$doc->write("<img src='files/my_image.gif'>");

my $filename = $doc->save_as("/path/to/some/file"); # or a filehandle

look at her go. she's building a whole Word doc out of vibes and HTML. no cap. πŸ¦‹


πŸ‘‘ DESCRIPTION πŸ‘‘

πŸŽ€ Goal πŸŽ€

So this module is one way to programatically generate documents targeted for Microsoft Word (MsWord). The slay part? It doesn't need MsWord to be installed, and it doesn't even require a Win32 machine β€” which is literally why the module is not in the Win32 namespace. it's giving platform independence. πŸ’–

Note : another, more recent approach for doing the same task is the module MsOffice::Word::Template, which has the great advantage of generating documents in genuine ".docx" format, instead of the MHTML format explained below. So for new projects, consider using MsOffice::Word::Template instead of the present module. (bestie, this is a soft launch of a better option. listen to it.)

🧚 MsWord and HTML 🧚

MsWord can read documents encoded in old native binary format, in Rich Text Format (RTF), in XML (either ODF or OOXML), or β€” and maybe this is less known β€” in HTML, with some special markup for pagination and other MsWord-specific features.

Such HTML documents are often in several parts, because attachments like images or headers/footers need to be in separate files. But since it's more convenient to carry all data in a single file, MsWord also supports the "MHTML" format (or "MHT" for short), i.e. an encapsulation of a whole HTML tree into a single file encoded in MIME multipart format. fancy, right? This format can be generated interactively from MsWord by calling the "SaveAs" menu and choosing the .mht extension.

okay this next bit is a whole saga, pay attention:

Documents saved with a .mht extension will not directly reopen in MsWord : when clicking on such documents, Windows chooses Microsoft Edge (in Internet Explorer mode) as the default display program. πŸ’€ However, these documents can be simply renamed with a .doc extension, and will then open directly in MsWord. By the way, the same can be done with XML or RTF documents. That is to say, MsWord is able to recognize the internal format of a file, without any dependency on the filename.

There is one unfortunate restriction, however : when the extension is .docx, MsWord does not accept any internal format different from OOXML. so that door is closed, periodt. So one has to either stick with the .doc extension, or choose a specific extension like .mswhtml and then associate this extension to the MsWord program : to do so, type the following command in a windows console

assoc .mswhtml=Word.Document.12 # for Office 2010, or .8 for Office 2003

⭐


🌈 Features of the module 🌈

"MsOffice::Word::HTML::Writer" helps you to programatically generate MsWord documents in MHT format. The advantage of this technique is that one can rely on standard HTML mechanisms for layout control, such as styles, tables, divs, etc. divs!! our beloved.

Of course this markup can be produced using your favorite HTML templating module; the added value of "MsOffice::Word::HTML::Writer" is to help building the MIME multipart file, and provide some abstractions for representing MsWord-specific features (headers, footers, fields, etc.).


πŸ’œ Advantages of MHT format πŸ’œ

The MHT format is probably the most convenient way for programmatic document generation, because

  • MsWord native binary format (used in versions up to 2003) was unpublished and therefore cannot be generated without the MsWord executable. (no source, no service, sorry πŸ’…)
  • remote control of the MsWord program through an OLE connection, as in Win32::Word::Writer, requires a local installation of Microsoft Office, and is not well suited for server-side generation because the MsWord program might hang or might open dialog boxes that require user input. imagine your server just… sitting there waiting for someone to click OK. nightmare.
  • generation of documents in RTF is possible, but authoring the models requires deep knowledge of the RTF structure --- see RTF::Writer.
  • authoring models in XML also requires deep knowledge of the XML structure.

Instead of working directly at the XML level, one could use the OpenOffice::OODoc distribution on CPAN, which provides programmatic access to the "ODF" XML format used by OpenOffice. MsWord is able to read and produce such ODF files, but this is not fully satisfactory because in that mode many MsWord features are disabled or restricted.

The XML format used by MsWord is called "OOXML". Modules Document::OOXML and MsOffice::Word::Surgeon on CPAN implement some operations on OOXML files, but have no support for creating a fresh document. The younger module MsOffice::Word::Template does provide an API for creating documents in OOXML format; the recommandation is to use that module instead of the present one. (again! she keeps getting recommended. she's that girl.)

"MsOffice::Word::HTML::Writer" allows you to produce documents even with little knowledge of MsWord. Besides, since the content is in HTML, it can be assembled with any HTML tool, and therefore also requires little knowledge of Perl. low barrier to entry, high reward. we love to see it. 🫢

One word of warning, however : opening MHT documents in MsWord is a bit slower than native binary or RTF documents, because MsWord needs to parse the HTML, compute the layout and convert it into its internal representation. Therefore MHT format is not recommended for very large documents. 😭

πŸ“ Usage πŸ“

"MsOffice::Word::HTML::Writer" is used in production at Geneva courts of law, for generating thousands of documents per day, from hundreds of models, with an architecture of reusable document parts implemented by Template Toolkit mechanisms (macros, blocks and views). thousands. per. day. she's employed employed. πŸ‘‘


πŸ’– METHODS πŸ’–

okay bestie, first the ✨golden rule✨ of this whole section:

  • method names that start with a verb? they might change the internal state of the writer object (think write, create_section).
  • method names that are nouns? they just hand you data back, no touching, no changes (think field, content, page_break).

periodt. that's the vibe check for the whole list.


🌸 new 🌸

my $doc = MsOffice::Word::HTML::Writer->new(%params);

Creates a brand new writer object, slay. All the params are optional and here's the tea on each one:

  • title β€” the document title, obviously πŸ’…
  • head β€” literally any HTML declarations you wanna drop into the head part of the generated document. inline CSS styles? links to attached stylesheets? go off, put them here.
  • hf_head β€” same energy but for the headers and footers HTML document. heads up (pun intended): MsWord requires headers and footers to be specified as divs in a separate HTML document. iykyk.
  • WordDocument β€” a hashref of options that gets included as an XML island in the HTML head. these correspond to the various options in the MsWord Tools/Options panel. they end up inside an XML element named <w:WordDocument>, and every child element automatically gets prefixed with w:. the hashref can have nested hashrefs too, like:
WordDocument => { View => 'Print',
                  Compatibility => {DoNotExpandShiftReturn => "",
                                    BreakWrappedTables     => ""} }

and bestie, you gotta find the names and values of these options from the Microsoft documentation, or from reverse engineering HTML files that MsWord generated. no shortcuts. 😭

  • charset β€” optional charset for MIME-encoding the document content. default is utf-8. you can specify another encoding like windows-1252, but in principle it won't change the final result, since Word will decode the specified charset anyway. and if the charset is different from utf-8, wide characters (anything with values higher than 0xFF) get replaced by their corresponding HTML numerical entities. so for example 'X' ("\N{BLACK HEART SUIT}") becomes &#9829;. cute, right? πŸŽ€
  • encode_fallback β€” a "fallback value" used as the third argument to encode in Encode when saving the file. this can be either a bitmask or a coderef, as documented in Encode. the default value is undef when the charset is utf-8. with other charsets, the default is this "pass-through" coderef:
sub {no utf8; sprintf "%c", shift}

this helps support documents with mixed encoding (for example when you're passing utf8 data to a template with native characters). in those situations, native characters get written "as is" to the final output instead of being swapped out for replacement characters. and if you don't want that behaviour? just pass an explicit undef as the argument and it's disabled. πŸ’œ

also!! parameters may be passed as a hashref instead of a hash. both work, no cap.

πŸ¦‹ write πŸ¦‹

$doc->write("<p>hello, world</p>");

Drops some HTML into the document body. that's it, that's the whole method. go write your lil heart out.


πŸŽ€ attach πŸŽ€

$doc->attach($localname, $filename);
$doc->attach($localname, "<", \$content);
$doc->attach($localname, "<&", $filehandle);

Adds an attachment into the document β€” it'll be encoded as a MIME part and it'll be accessible under files/$localname. so iconic.

the remaining arguments to attach specify the source of the attachment, and they get passed directly to open in perlfunc, which means you get all that same API flexibility: a filename, a reference to a memory variable, a reference to another filehandle, whatever you want. chef's kiss. ✨


πŸ‘‘ create_section πŸ‘‘

$doc->create_section(
  page => {size   => "21.0cm 29.7cm",
           margin => "1.2cm 2.4cm 2.3cm 2.4cm"},
  header => sprintf("Section 2, page %s of %s",
                                $doc->field('PAGE'),
                                $doc->field('NUMPAGES')),
  footer => sprintf("printed at %s",
                                $doc->field('PRINTDATE')),
  new_page => 1, # or 'always, or 'left', or 'right'
);

Opens a new section inside the document. or β€” plot twist β€” if you call this before any write, it sets up the pagination parameters for the first section instead. after this, every write call adds content to that section, until the next create_section call comes along and steals the spotlight. main character energy, fr fr.

all the pagination parameters are optional and can be given either as a hash or as a hashref. here's what's on the menu:

  • page β€” hashref of CSS page styles, such as:
    • size β€” paper size (for example "21cm 29.7cm")
    • margin β€” margins (top right bottom left).
    • header_margin β€” margin for header
    • footer_margin β€” margin for footer
    • page_numbers β€” initial value for page numbers within this section
    • paper_source β€” parameters for paper source within this section. and ngl, the values for these parameters must be reverse engineered from MsWord HTML output. πŸ’€
  • header β€” header content (in HTML)
  • first_header β€” header content for the first page of that section.
  • footer β€” footer content (in HTML).
  • first_footer β€” footer content for the first page.
  • new_page β€” if true, a page break gets inserted before the new section. if the argument is the word 'left' or 'right', one or two page breaks get inserted so the next page is formatted as a left (right) page. if the argument is a numeric true value, it's translated into the word 'always', which tells MsWord to insert a page break in any case. no skipping, bestie.

🌈 save_as 🌈

$doc->save_as($target);

Generates the MIME document and saves it at the given $target, which can be a filename or a filehandle. if there's no extension in the filename, the extension .doc gets added by default β€” and that's what's returned as the result of the method call. so thoughtful. 🫢


⭐ content ⭐

Returns the whole MIME-encoded document as a single string. this is used internally by the save_as method, but calling it directly is useful if you don't wanna save the document to a file and instead wanna do something else with it β€” embed it in a message, stuff it in a ZIP file, return it as an HTTP response. the possibilities are literally endless, bestie. πŸ’…


πŸ’€ page_break πŸ’€

$doc->write($doc->page_break);

Returns HTML markup for encoding a page break within the same section. another way of inserting a page break is to create a new section with a new_page parameter β€” peep create_section for that. two roads, same destination. πŸ›£οΈ


πŸ“ tab πŸ“

my $html = $doc->tab($n_tabs);

Returns HTML markup for encoding one or several tabs. if $n_tab is omitted, it defaults to 1. simple, clean, iconic.


🧚 field 🧚

my $html = $doc->field($fieldname, $args, $content,
                       $prevent_html_entity_encoding);

Returns HTML markup for a MsWord field. let's break it down:

  • optional $args is a string with arguments or flags for the field. for the list of field names and their associated arguments or flags, check the MsWord help documentation. i don't make the rules. πŸ“–
  • optional $content is the initial displayed content for the field. and the reason you'd want that? because unfortunately MsWord does not immediately compute the field content when opening the document 😭 β€” users will have to explicitly request to update all fields by selecting the whole document and then hitting the F9 key. so rude of it.
  • optional $prevent_html_entity_encoding is a boolean that prevents the automatic translation of <, > and & characters into the HTML entities &lt, &gt and &amp;. super useful if you wanna insert some rich text. ✨

and here are some examples, because we love a demo:

my $header = sprintf "%s of %s", $doc->field('PAGE'),
                                 $doc->field('NUMPAGES');
my $footer = sprintf "created at %s, printed at %s",
               doc->field(CREATEDATE => '\\@ "d MM yyyy"'),
               doc->field(PRINTDATE  => '\\@ "dddd d MMMM yyyy" \\* Upper');
my $quoted = $doc->field('QUOTE', '"hello, world"', 'hello, world');

πŸ’œ quote πŸ’œ

my $html = $doc->quote($text, $prevent_html_entity_encoding);

A shortcut to produce a QUOTE field (see that last field example right above πŸ‘†). the optional $prevent_html_entity_encoding argument is explained back in the field method, so scroll up if you forgot. we got you. 🫢

HTML for MsWord 🌸

Bestie, listen β€” MsWord does NOT support the full HTML and CSS standard, and that's just the reality we live in. So authoring MHT documents is gonna involve some trial and error, fr. Basic divs, spans, paragraphs and tables are reasonably supported, together with their common CSS properties β€” that part's fine, we eat those for breakfast πŸ’…. But fancier features like floats, absolute positioning, etc. may yield some surprises. Not always the cute kind of surprise. πŸ™ˆ

To specify widths and heights, you'll get better results by using CSS properties rather than attributes of the HTML table model. No cap.

And if you're struggling to implement some specific feature? Try to see what MsWord itself does with that feature when saving a document in HTML format (plain HTM, not MHT!). The generated HTML is quite verbose β€” like, so verbose 😭 β€” but after eliminating unnecessary tags one can sometimes figure out which are the key tags (they start with "o:" or "w:") or the key attributes (they start with "mso-") which correspond to the desired functionality. Reverse-engineering era, honestly. ✨


Collaboration with the Template Toolkit πŸ¦‹

The Template Toolkit (TT for short) is a very helpful tool for generating the HTML. Below are some hints about collaboration between the two modules.

Client code calls both TT and Word::HTML::Writer

Mode number one: use the Template Toolkit for generating various document parts, and then assemble them into "MsOffice::Word::HTML::Writer".

 use Template;
 my $tmpl_app = Template->new(%options);
 $tmpl_app->process("doctmpl/html_head.tt", \%data, \my $html_head);
 $tmpl_app->process("doctmpl/body.tt",      \%data, \my $body);
 $tmpl_app->process("doctmpl/header.tt",    \%data, \my $header);
 $tmpl_app->process("doctmpl/footer.tt",    \%data, \my $footer);

 use MsOffice::Word::HTML::Writer;
 my $doc = MsOffice::Word::HTML::Writer->new(
   title  => $data{title},
   head   => $html_head,
 );
 $doc->create_section(
   header => $header,
   footer => $footer,
 );
 $doc->write($body);
 $doc->save_as("/path/to/some/file");

This architecture is straightforward, bestie, but various document parts are split into several templates, which might be inconvenient when maintaining a large body of document templates. Lowkey annoying, ngl.

HTML parts as blocks in a single template

Document parts might also be encoded as blocks within one single template:

 [% BLOCK html_head %]
 <style>...CSS...</style>
 [% END; # BLOCK html_head %]

 [% BLOCK body %]
   Hello, world
 [% END; # BLOCK body %]

 etc.

Then the client code calls each block in turn to gather the various parts:

 use Template::Context;
 my $tmpl_ctxt = Template::Context->new(%options);
 my $tmpl      = $tmpl_ctxt->template("doctmpl/all_blocks.tt");
 my $html_head = $tmpl_ctxt->process($tmpl->blocks->{html_head}, \%data);
 my $body      = $tmpl_ctxt->process($tmpl->blocks->{body},      \%data);
 my $header    = $tmpl_ctxt->process($tmpl->blocks->{header},    \%data);
 my $footer    = $tmpl_ctxt->process($tmpl->blocks->{footer},    \%data);

 # assemble into MsOffice::Word::HTML::Writer, same as before

Template toolkit calls MsOffice::Word::HTML::Writer

Okay now let's look at a different architecture, and this one's kinda giving main character energy: the client code calls the Template toolkit, which in turn calls "MsOffice::Word::HTML::Writer". πŸŽ€

The most common way to call modules from TT is to use a TT plugin; but since there is currently no TT plugin for "MsOffice::Word::HTML::Writer", we will just tell TT that templates can load regular Perl modules, by turning on the "LOAD_PERL" option.

The client code looks like any other TT application; but the output of the process method is a fully-fledged MHT document, instead of plain HTML. Iconic.

 use Template;
 my $tmpl_app = Template->new(LOAD_PERL => 1, %other_options);
 $tmpl_app->process("doc_template.tt", \%data, \my $msword_doc);

Within "doc_template.tt", we have:

 [% # main entry point

    # gather various parts
    SET html_head = PROCESS html_head;
    SET header    = PROCESS header;
    SET footer    = PROCESS footer;
    SET body      = PROCESS body;

    # create Word::HTML::Writer object
    USE msword = MsOffice.Word.HTML.Writer(head=html_head);

    # setup section format
    CALL msword.create_section(
       page => {size          => "21.0cm 29.7cm",
                margin        => "1cm 2.5cm 1cm 2.5cm",
                header_margin => "1cm",
                footer_margin => "0cm",},
       header => header,
       footer => footer
     );

     # write the body
    CALL msword.write(body);

    # return the MIME-encoded MsWord document
    msword.content();  %]

 [% BLOCK html_head %]
 ...

Inheritance through TT views πŸ‘‘

The above architecture can be refined one step further, by using TT views to encapsulate documents. Views have an inheritance mechanism, so it becomes possible to define families of document templates, that inherit properties or methods from common ancestors. Let us start with generic_letter.tt2, a generic letter template:

 [% VIEW generic_letter
       title="Generic letter template";

      BLOCK main;
        USE msword = MsOffice.Word.HTML.Writer(
           title => view.title,
           head  => view.html_head(),
        );
        view.write_body();
        msword.content();
      END; # BLOCK main

      BLOCK write_body;
        CALL msword.create_section(
           page   => {size          => "21.0cm 29.7cm",
                      margin        => "1cm 2.5cm 1cm 2.5cm"},
           header => view.header(),
           footer => view.footer()
        );
        CALL msword.write(view.body());
      END; # BLOCK write_body

      BLOCK body;
        view.letter_head();
        view.letter_body();
      END; # BLOCK body

      BLOCK letter_body; %]
       Generic letter body; please override BLOCK letter_body in subviews
   [% END; # BLOCK letter_body;

      # ... other blocks for header, footer, letter_head, etc.

    END; # VIEW generic_letter

 [% # call main() method if this templated was loaded directly
    letter.main() UNLESS component.caller %]

This is quite similar to an object-oriented class, bestie: assignments within the view are like object attributes (i.e. the "title" variable), and blocks within the view are like methods. It's giving OOP, but make it templates. ✨

After the end of the view, we call the "main" method, but only if that view was called directly from client code. If the view is inherited, as displayed below, then the call to "main" will be from the subview.

Now we can define a specific letter template that inherits from the generic letter and overrides the "letter_body" block:

 [% PROCESS generic_letter.tt2; # loads the parent view

    VIEW advertisement;

      BLOCK letter_body; %]

        <p>Dear [% receiver.name %],</p>
        <p>You have won a wonderful [% article %].
           Just call us at [% sender.phone %].</p>
        <p>Best regards,</p>
        [% view.signature(name => sender.name ) %]

 [%   END; # BLOCK letter_body
    END; # VIEW advertisement

    advertisement.main() UNLESS component.caller %]

πŸ’­ TO DO

Okay so here's the wishlist, and it's still a wishlist:

  • link same header/footers across several sections
  • multiple columns
  • watermarks (I tried hard to reverse engineer MsWord behaviour, but it still doesn't work ... couldn't figure out all details of VML markup)

Contributions welcome! 🫢 Come through.


πŸ‘‘ AUTHOR

Laurent Dami, "<dami AT cpan DOT org>"


πŸ› BUGS

Please report any bugs or feature requests to <https://github.com/damil/MsOffice-Word-HTML-Writer/issues>.

Fr fr, if something's broken, that's the spot. Don't suffer in silence, bestie. πŸ’€

🌈 SEE ALSO

Win32::Word::Writer, RTF::Writer, Spreadsheet::WriteExcel, OpenOffice::OODoc, Document::OOXML, MsOffice::Word::Surgeon, MsOffice::Word::Template.


Copyright 2009-2023 Laurent Dami, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


And that's the whole page, bestie!! πŸŽ€βœ¨ This one shipped as part of the User Contributed Perl Documentation, and the footer vibes were perl v5.36.0 dated 2023-09-29, under the MsOffi...Writer(3pm) name (yes, the title is truncated exactly like that β€” that's just how the man page tooling do 😭). Go write some MHT docs, you absolute legend. Slay. πŸ’…πŸ¦‹

πŸ“¦ where this page comes from