use IO::Socket; use Win32::OLE qw(in with); use Win32::OLE::Const 'Microsoft Word'; use Win32::OLE::Variant; use IO::Handle; use POSIX; ## This is a server that accepts HTML documents on port ## 7422, returning a Word document. As far as I know, it ## can only be run with ActiveState ActivePerl on Windows ## with Microsoft Word installed. Also, if using SFU, ## must run from C:\SFU\Perl\bin\Perl.exe, not the ## POSIX version at C:\SFU\usr\local\bin\perl. The POSIX ## version has no support for Win32::OLE. If anyone hacks ## OLE support into the POSIX version, let me know at: ## . my $server_port = 7422; my $current_time = time(); my $word; eval {$word = Win32::OLE->GetActiveObject('Word.Application')}; die "Word not installed" if $@; unless (defined $word) { $word = Win32::OLE->new('Word.Application', sub { $_[0]->Quit; }) or die "Cannot start Word"; } Win32::OLE->Option(Warn => 3); $server = IO::Socket::INET->new(LocalPort => $server_port, Proto => 'tcp', Type => SOCK_STREAM, Reuse => 1, Listen => 5) or die "Could not open server on tcp/$server_port : $@\n"; print STDERR "Server startup in ", time() - $current_time, " seconds on tcp/$server_port\n"; while ($client = $server->accept()) { print STDERR "New connection\n"; ###TODO: GET REAL TEMPORARY FILENAME (this is hit-and-miss) my $file = "c:\\SFU\\tmp" . POSIX::tmpnam() . "0.html"; ###RECEIVE HTML FROM CLIENT open(IFILE, ">$file") or next; #TODO: log error my $i = 0; my $buf = ""; while (read($client, $buf, 1024, 0) > 0) { print IFILE $buf; $i++; } print STDERR "$i 1024-byte input buffers processed\n"; undef $i; undef $buf; close(IFILE); print STDERR "Open temporary $file\n"; #TODO: if verbose my $doc = $word->{'Documents'}->Open("$file") or next; #TODO: log error print STDERR "Write temporary $file.doc\n"; #TODO: if verbose $doc->SaveAs("$file.doc", { 'FileFormat' => wdFormatDocument }); $doc->Close(); undef $doc; ###SEND DOC BACK TO CLIENT open(OFILE, "<$file.doc") or die "Could not open Office Document"; #TODO: log error binmode(OFILE); my $buf = ""; my $i = 0; while (read(OFILE, $buf, 1024, 0) > 0) { print $client $buf; $i++; } print STDERR "$i 1024-byte output buffers processed\n"; undef $i; undef $buf; close(OFILE); ###REMOVE TEMPORARY HTML & DOC unlink("$file") or print STDERR "ERROR: could not delete $file\n"; unlink("$file.doc") or print STDERR "ERROR: could not delete $file.doc\n"; $client->close; print STDERR "Done with connection\n"; } undef $word; close($server);