s in a separate HTML document).
=item WordDocument
a hashref of options to include as an XML island in the
HTML C, corresponding to various options in the
MsWord "Tools/Options" panel. These will be included
in a XML element named C<<
>>, and
all children elements will be automatically prefixed
by C. The hashref may contain nested hashrefs, such as
WordDocument => { View => 'Print',
Compatibility => {DoNotExpandShiftReturn => "",
BreakWrappedTables => ""} }
Names and values of options
must be found from the Microsoft documentation, or from
reverse engineering of HTML files generated by MsWord.
=item charset
an optional charset for MIME-encoding the document content.
The default is C. Another encoding like C
may be specified, but in principle this will not change the final
result, since Word will decode the specified charset.
If the charset is different from C, wide characters (those
with values higher than C<0xFF>) will be replaced by their corresponding
HTML numerical entities; so for example '♥' (C<< \N{BLACK HEART SUIT} >>)
will be replaced by C<< ♥ >>.
=item encode_fallback
a "fallback value" used as third argument to L, when saving the file.
This can be either a bitmask or a coderef, as documented in L.
The default value is C when the charset is C.
With other charsets, the default is the following "pass-through" coderef :
sub {no utf8; sprintf "%c", shift}
This helps to support documents with mixed encoding (for example when passing utf8 data
to a template with native characters). In such situations, native characters will be
written "as is" to the final output, instead of being substituted with replacement characters.
This behaviour can be disabled by passing an explicit C as argument.
=back
Parameters may also be passed as a hashref instead of a hash.
=head2 write
$doc->write("hello, world
");
Adds some HTML into the document body.
=head2 attach
$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 C.
The remaining arguments to C specify the source of the attachment;
they are directly passed to L and therefore have the same
API flexibility : you can specify a filename, a reference to a memory
variable, a reference to another filehandle, etc.
=head2 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 within the document
(or, if this is called before any L,
setups pagination parameters for the first section).
Subsequent calls to the L method will add content to
that section, until the next L call.
Pagination parameters are all optional and may be given
either as a hash or as a hashref; accepted parameters are :
=over
=item page
Hashref of CSS page styles, such as :
=over
=item size
Paper size (for example C<21cm 29.7cm>)
=item margin
Margins (top right bottom left).
=item header_margin
Margin for header
=item footer_margin
Margin for footer
=item page_numbers
Initial value for page numbers within this section
=item paper_source
Parameters for paper source within this section
(values for these parameters must be reverse engineered from MsWord HTML
output)
=back
=item header
Header content (in HTML)
=item first_header
Header content for the first page of that section.
=item footer
Footer content (in HTML).
=item first_footer
Footer content for the first page.
=item new_page
If true, a page break will be inserted before the new section.
If the argument is the word C<'left'> or C<'right'>, one or two
page breaks will be inserted so that the next page is formatted
as a left (right) page. If the argument is a numeric true value, it
is translated into the word 'always', which tells MsWord to
insert a page break in any case.
=back
=head2 save_as
$doc->save_as($target);
Generates the MIME document and saves it at the given C<$target>,
which can be a filename or a filehandle.
If no extension is present in the filename, file extension F<.doc> will be added
by default; this is returned as the result from the method call.
=head2 content
Returns the whole MIME-encoded document as a single string; this is
used internally by the L 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.
=head2 page_break
$doc->write($doc->page_break);
Returns HTML markup for encoding a page break I.
Another way of inserting a page break is to create a new section
with an C parameter -- see L.
=head2 tab
my $html = $doc->tab($n_tabs);
Returns HTML markup for encoding one or several tabs. If C<$n_tab> is
omitted, it defaults to 1.
=head2 field
my $html = $doc->field($fieldname, $args, $content,
$prevent_html_entity_encoding);
Returns HTML markup for a MsWord field.
Optional C<$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.
Optional C<$content> is the initial displayed content for the
field (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).
Optional C<$prevent_html_entity_encoding> is a boolean
that prevents the automatic translation of C<< < >>, C<< > >> and
C<< & >> characters into HTML entities C<< < >>, C<< > >> and
C<< & >>. This is useful if you want to insert some rich text.
Here are some examples :
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');
=head2 quote
my $html = $doc->quote($text, $prevent_html_entity_encoding);
Shortcut to produce a QUOTE field (see last field example just above).
The optional C<$prevent_html_entity_encoding> argument is explained in the
L method.
=head1 AUTHORING MHT DOCUMENTS
=head2 HTML for MsWord
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 C or C) or the
key attributes (they start with C) which correspond
to the desired functionality.
=head2 Collaboration with the Template Toolkit
The L (TT for short)
is a very helpful tool for generating the HTML.
Below are some hints about collaboration between
the two modules.
=head3 Client code calls both TT and Word::HTML::Writer
The first mode is to use the Template Toolkit for
generating various document parts, and then assemble
them into C.
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.
=head3 HTML parts as blocks in a single template
Document parts might also be encoded as blocks within one
single template :
[% BLOCK html_head %]
[% 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
=head3 Template toolkit calls MsOffice::Word::HTML::Writer
Now let's look at a different architecture: the client code
calls the Template toolkit, which in turn calls
C.
The most common way to call modules from TT is to use
a I; but since there is currently
no TT plugin for C,
we will just tell TT that templates can load regular
Perl modules, by turning on the C option.
The client code looks like any other TT application; but the output of
the L 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 C, 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 %]
...
=head3 Inheritance through TT views
The above architecture can be refined one step further,
by using L 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 F,
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 : assignments
within the view are like object attributes (i.e. the C
variable), and blocks within the view are like methods.
After the end of the view, we call the C method, but
only if that view was called directly from client code.
If the view is inherited, as displayed below, then the
call to C will be from the subview.
Now we can define a specific letter template that inherits
from the generic letter and overrides the C block :
[% PROCESS generic_letter.tt2; # loads the parent view
VIEW advertisement;
BLOCK letter_body; %]
Dear [% receiver.name %],
You have won a wonderful [% article %].
Just call us at [% sender.phone %].
Best regards,
[% view.signature(name => sender.name ) %]
[% END; # BLOCK letter_body
END; # VIEW advertisement
advertisement.main() UNLESS component.caller %]
=head1 TO DO
- 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!
=head1 AUTHOR
Laurent Dami, C<< >>
=head1 BUGS
Please report any bugs or feature requests to
L.
=head1 SEE ALSO
L, L, L,
L, L, L,
L.
=head1 COPYRIGHT & LICENSE
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.
MsOffice-Word-HTML-Writer-1.10/t 000755 000000 000000 0 14463375373 16664 5 ustar 00unknown unknown 000000 000000 MsOffice-Word-HTML-Writer-1.10/t/00-load.t 000444 000000 000000 313 11711662010 20273 0 ustar 00unknown unknown 000000 000000 #!perl -T
use Test::More tests => 1;
BEGIN {
use_ok( 'MsOffice::Word::HTML::Writer' );
}
diag( "Testing MsOffice::Word::HTML::Writer $MsOffice::Word::HTML::Writer::VERSION, Perl $], $^X" );
MsOffice-Word-HTML-Writer-1.10/t/01_word_document.t 000444 000000 000000 3057 14463352641 22355 0 ustar 00unknown unknown 000000 000000 #!perl
use utf8;
use Test::More;
use MsOffice::Word::HTML::Writer;
my $doc = MsOffice::Word::HTML::Writer->new(
title => "Demo",
WordDocument => {View => 'Print',
Compatibility => {DoNotExpandShiftReturn => ""} },
);
$doc->write("hello, world");
my $br = $doc->page_break;
$doc->write($br . "new page after manual break");
$doc->create_section(new_page => 'right');
$doc->write("new page after right section break");
$doc->create_section(new_page => 1);
$doc->write("new page after normal section break");
my $txt = "this is an April 1st joke";
$doc->write($doc->quote($txt, 'true')); # prevent HTML entity encoding
$doc->write("
27 Ocak 1756 yılında Salzbug'da doğmuş, 5 Aralık 1791 yılında Viyana'da ölmüştür");
$doc->write("
il était une bergère");
my $content = $doc->content;
like $content, qr(Print), "View => print";
like $content, qr(), "Compatibility => DoNotExpandShiftReturn";
my @break_right = $content =~ /page-break-before:right/g;
is scalar(@break_right), 1, "page break:right";
like $content, qr(April 1st joke), "prevent HTML entity encoding";
like $content, qr/\bdoÄŸmuÅŸ\b/, "UTF8 word";
like $content, qr/\bbergère\b/, "bergère";
done_testing;
$doc->save_as("01_word_document.doc") if $ENV{MWHW_SAVE_TEST_DOCS};
MsOffice-Word-HTML-Writer-1.10/t/02_latin1.t 000444 000000 000000 2760 14463352662 20700 0 ustar 00unknown unknown 000000 000000 #!perl
use Test::More;
use MsOffice::Word::HTML::Writer;
my $doc = MsOffice::Word::HTML::Writer->new(
title => "Demo",
WordDocument => {View => 'Print',
Compatibility => {DoNotExpandShiftReturn => ""} },
charset => "iso-8859-1",
);
$doc->write("hello, world");
my $br = $doc->page_break;
$doc->write($br . "new page after manual break");
$doc->create_section(new_page => 'right');
$doc->write("new page after right section break");
$doc->create_section(new_page => 1);
$doc->write("new page after normal section break");
my $txt = "this is an April 1st joke";
$doc->write($doc->quote($txt, 'true')); # prevent HTML entity encoding
$doc->write("
27 Ocak 1756 y\x{0131}l\x{0131}nda Salzbug\'da do\x{011F}mu\x{015F}, 5 Aral\x{0131}k 1791 y\x{0131}l\x{0131}nda Viyana\'da ölmü\x{015F}tür");
$doc->write("
il était une bergère");
my $content = $doc->content;
like($content, qr(Print), "View => print");
like($content, qr(),
"Compatibility => DoNotExpandShiftReturn");
my @break_right = $content =~ /page-break-before:right/g;
is(scalar(@break_right), 1, "page break:right");
like($content, qr(April 1st joke),
"prevent HTML entity encoding");
my $utf8_word = 'doğmuş';
like($content, qr/$utf8_word/, 'UTF8 support');
like($content, qr/\bbergère\b/, 'bergère');
done_testing;
$doc->save_as("02_latin1.doc") if $ENV{MWHW_SAVE_TEST_DOCS};
MsOffice-Word-HTML-Writer-1.10/t/03_buggy_accents.t 000444 000000 000000 1326 14463352741 22321 0 ustar 00unknown unknown 000000 000000 #!perl
use utf8;
use Test::More;
use MsOffice::Word::HTML::Writer;
# prior to v1.09, MsWord would open these documents as Japanese !
make_doc("03_buggy_accents_default_utf8.doc");
make_doc("03_buggy_accents_cp1252.doc", charset => "windows-1252");
sub make_doc {
my ($filename, %options) = @_;
my $doc = MsOffice::Word::HTML::Writer->new(%options);
$doc->write("ééèèéèéèèééèççççà à à à à Ã
") for 1..2;
$doc->write("ACCUSÉ DE RÉCEPTION
");
$doc->write("tué dans l’oeuf
");
my $content = $doc->content;
like $content, qr/ACCUSÉ/, "content accusé for $filename";
$doc->save_as($filename) if $ENV{MWHW_SAVE_TEST_DOCS};
}
done_testing;
MsOffice-Word-HTML-Writer-1.10/t/04_mixed_encoding.t 000444 000000 000000 2033 14463374207 22456 0 ustar 00unknown unknown 000000 000000 #!perl
use utf8;
use Test::More;
use MsOffice::Word::HTML::Writer;
use Encode qw/encode decode/;
my $utf8 = "tué dans l’œuf";
my $cp1252 = encode("windows-1252", $utf8);
my $mixed = "native string: $cp1252, utf8 string: $utf8";
my %expected_content_for_charset = (
"windows-1252" => qr/native string: tué dans l’œuf, utf8 string: tué dans l’œuf/,
"utf-8" => qr/native string: tué dans l\222\234uf, utf8 string: tué dans l’œuf/,
);
while (my ($charset, $expected) = each %expected_content_for_charset) {
qr/native: tué dans l’œuf, utf8: tué dans l’œuf/,
my $doc = MsOffice::Word::HTML::Writer->new(charset => $charset);
$doc->write($mixed);
my $content = $doc->content;
open my $fh, ">", \my $file_in_memory;
$doc->save_as($fh);
my $decoded_file = decode($charset, $file_in_memory);
like $decoded_file, $expected, "$charset doc";
$doc->save_as("04_mixed_encoding_$charset.doc") if $ENV{MWHW_SAVE_TEST_DOCS};
}
done_testing;
MsOffice-Word-HTML-Writer-1.10/xt 000755 000000 000000 0 14463375373 17054 5 ustar 00unknown unknown 000000 000000 MsOffice-Word-HTML-Writer-1.10/xt/pod-coverage.t 000444 000000 000000 345 14405324201 21707 0 ustar 00unknown unknown 000000 000000 #!perl -T
use Test::More;
eval "use Test::Pod::Coverage 1.04";
plan skip_all => "Test::Pod::Coverage 1.04 required for testing POD coverage" if $@;
my $params = {trustme => [
]};
all_pod_coverage_ok($params);
MsOffice-Word-HTML-Writer-1.10/xt/pod.t 000444 000000 000000 222 13036375004 20116 0 ustar 00unknown unknown 000000 000000 #!perl -T
use Test::More;
eval "use Test::Pod 1.14";
plan skip_all => "Test::Pod 1.14 required for testing POD" if $@;
all_pod_files_ok();