MsOffice::Word::HTML::Writer - Writing documents for MsWord in HTML format
use MsOffice::Word::HTML::Writer; my $doc = MsOffice::Word::HTML::Writer->new(title => "My new doc"); $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"}, 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, ); $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'>"); $doc->save_as("/path/to/some/file");
The present module is one way to programatically generate documents targeted for Microsoft Word (MsWord). It doesn't need MsWord to be installed, and doesn't even require a Win32 machine (which is why it is not in the Win32 namespace).
Win32
MsWord can read documents encoded in native binary format, in Rich Text Format (RTF), in WordML (an XML dialect), or -- 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; however, since it is 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. This format can be generated interactively from MsWord by calling the "SaveAs" menu and choosing the .mht extension.
Documents saved with a .mht extension will not directly reopen in MsWord : when clicking on such documents, Windows chooses Internet Explorer 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 WordML or RTF documents. That is to say, MsWord is able to recognize the internal format of a file, without any dependency on the filename.
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. 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.).
MsOffice::Word::HTML::Writer
The MHT format is probably the most convenient way for programmatic document generation, because
unlike Excel, MsWord native binary format is unpublished and therefore cannot be generated without the MsWord executable.
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 servers because the MsWord program might hang or might open dialog boxes that require user input.
generation of documents in RTF is possible, but requires deep knowledge of the RTF structure --- see RTF::Writer.
generation of documents in "WordML" also requires deep knowledge of WordML structure.
By contrast, MsOffice::Word::HTML::Writer allows you to produce documents even with little knowledge of MsWord. One word of warning, however : opening MHT documents in MsWord is 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 large documents.
Note : this first release of MsOffice::Word::HTML::Writer is still in an exploratory phase; the programming interface may change in future versions.
General convention : method names that start with a verb may change the internal state of the writer object (for example "write", "create_section"); method names that are nouns return data without modifying the internal state (for example "field", "content", page_break).
my $doc = MsOffice::Word::HTML::Writer->new(%params);
Creates a new writer object. Optional parameters are :
document title
any HTML declarations you may want to include in the head part of the generated document (for example inline CSS styles or links to attached stylesheets).
head
any HTML declarations you may want to include in the head part of the headers and footers HTML document (MsWord requires headers and footers to be specified as divs in a separate HTML document).
div
Parameters may also be passed as a hashref instead of a hash.
$doc->write("<p>hello, world</p>");
Adds some HTML into the document body.
$doc->attach($localname, $filename); $doc->attach($localname, "<", \$content); $doc->attach($localname, "<&", $filehandle);
Adds an attachment into the document; the attachment will be encoded as a MIME part and will be accessible under files/$localname.
files/$localname
The remaining arguments to attach specify the source of the attachment; they are directly passed to "open" in perlfunc and therefore have the same API flexibility : you can specify a filename, a reference to a memory variable, a reference to another filehandle, etc.
attach
$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, );
Opens a new section within the document (or, if this is called before any "write", setups pagination parameters for the first section). Subsequent calls to the "write" method will add content to that section, until the next "create_section" call.
Pagination parameters are all optional and may be given either as a hash or as a hashref; accepted parameters are :
Hashref of CSS page styles, such as :
Paper size (for example 21cm 29.7cm)
21cm 29.7cm
Margins (top right bottom left).
Margin for header
Margin for footer
Header content (in HTML)
Header content for the first page of that section.
Footer content (in HTML).
Footer content for the first page.
If true, a page break will be inserted before the new section.
$doc->save_as("/path/to/some/file");
Generates the MIME document and saves it at the given location. If no extension is present, file extension .doc will be added by default to the filename.
Returns the whole MIME-encoded document as a single string; this is used internally by the "save_as" method. Direct call is useful if you don't want to save the document into a file, but want to do something else like embedding it in a message or a ZIP file, or returning it as an HTTP response.
Returns HTML markup for encoding a page break.
my $html = $doc->field($fieldname, $args);
Returns HTML markup for a MsWord field. Optional $args is a string with arguments or flags for the field. See MsWord help documentation for the list of field names and their associated arguments or flags. Here are some examples :
$args
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');
MsWord does not support the full HTML and CSS standard, so authoring MHT documents requires some trial and error. Basic divs, spans, paragraphs and tables, are reasonably supported, together with their common CSS properties; but fancier features like floats, absolute positioning, etc. may yield some surprises.
To specify widths and heights, you will get better results by using CSS properties rather than attributes of the HTML table model.
In case of difficulties for implementing specific features, try to see what MsWord does with that feature when saving a document in HTML format (plain HTM, not MHT!). The generated HTML is quite 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.
o:
w:
mso-
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.
The first mode is to 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, but various document parts are split into several templates, which might be inconvenient when maintaining a large body of document templates.
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
Now let's look at a different architecture: 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.
LOAD_PERL
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.
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
doc_template.tt
[% # 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 %] ...
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 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 : assignments within the view are like object attributes (i.e. the title variable), and blocks within the view are like methods.
title
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.
main
Now we can define a specific letter template that inherits from the generic letter and overrides the letter_body block :
letter_body
[% 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 %]
This module is still exploratory; many features need to be added. For example:
- odd/even pages - 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!
Laurent Dami, <laurent DOT dami AT etat DOT geneve DOT ch>
<laurent DOT dami AT etat DOT geneve DOT ch>
Please report any bugs or feature requests to bug-win32-word-html-writer at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=MsOffice-Word-HTML-Writer. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
bug-win32-word-html-writer at rt.cpan.org
You can find documentation for this module with the perldoc command.
perldoc MsOffice::Word::HTML::Writer
You can also look for information at:
AnnoCPAN: Annotated CPAN documentation
http://annocpan.org/dist/MsOffice-Word-HTML-Writer
CPAN Ratings
http://cpanratings.perl.org/d/MsOffice-Word-HTML-Writer
RT: CPAN's request tracker
http://rt.cpan.org/NoAuth/Bugs.html?Dist=MsOffice-Word-HTML-Writer
Search CPAN
http://search.cpan.org/dist/MsOffice-Word-HTML-Writer
Win32::Word::Writer, RTF::Writer, Spreadsheet::WriteExcel.
Copyright 2009 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.
To install MsOffice::Word::HTML::Writer, copy and paste the appropriate command in to your terminal.
cpanm
cpanm MsOffice::Word::HTML::Writer
CPAN shell
perl -MCPAN -e shell install MsOffice::Word::HTML::Writer
For more information on module installation, please visit the detailed CPAN module installation guide.