, ,

Magic Folder to Convert DOC and OpenOffice to PDF

Most of the information in this post is derived from http://www.tech-faq.com/convert-word-to-pdf.html. The code’s reposted here as a service, because the code there needs some editing.

Also, a useful thread about executing OOo macros is at http://www.oooforum.org/forum/viewtopic.phtml?t=2619.

Here’s the code to automate the opening and saving of a file as PDF, using Open Office. Paste this into your standard macros.

Sub ConvertWordToPDF(cFile)
    cURL = ConvertToURL(cFile)
    ' Open the document.
    ' Just blindly assume that the document is of a type that OOo will
    ' correctly recognize and open — without specifying an import filter.
    oDoc = StarDesktop.loadComponentFromURL(cURL, "_blank", 0, Array(MakePropertyValue("Hidden", True), ))
    cFile = Left(cFile, Len(cFile) - 4) + ".pdf"
    cURL = ConvertToURL(cFile)
    ' Save the document using a filter.
    oDoc.storeToURL(cURL, Array(MakePropertyValue("FilterName", "writer_pdf_Export"), ))
    oDoc.close(True)
End Sub

Function MakePropertyValue( Optional cName As String, Optional uValue ) As com.sun.star.beans.PropertyValue
    Dim oPropertyValue As New com.sun.star.beans.PropertyValue
    If Not IsMissing( cName ) Then
        oPropertyValue.Name = cName
        EndIf
        If Not IsMissing( uValue ) Then
            oPropertyValue.Value = uValue
            EndIf
            MakePropertyValue() = oPropertyValue
        End Function
        
Sub test()
    ConvertWordToPDF("file:///home/johnk/Desktop/cooking websites article.odt")
End Sub

To use this macro, you should execute it from the command line. Here’s a shell script that helps.


#!/bin/sh
DIR=$(pwd)
DOC=$DIR/$1
/user/bin/oowriter-invisible "macro://Standard.Module1.ConvertWordToPDF($DOC)"

And last but not least, my addition – a script that watches a folder called pdeffer and converts DOC files to PDF. The only problem is that only simple, textual files with graphics will work. More complex layouts will fail.

To use it, execute it in the background or start it in a “screen” session. It’s not a full-fledged service (and won’t be).

#! /usr/bin/perl

chdir '/home/johnk/pdeffer';

use Cwd;

%docs = ();
%pdfs = ();

sub main() {
    print "checking\n";
    opendir DH, '.';
    while ( $file = readdir(DH) ) {
        if ( $file =~ /.doc$/ ) {
            $docs{$file} = 1;
        }
        if ( $file =~ /.pdf$/ ) {
            $pdfs{$file} = 1;
        }
    }
    closedir DH;

    foreach $d ( keys(%docs) ) {
        print "$d\n";
        $p = $d;
        $p =~ s/.doc/.pdf/;
        next if ( $pdfs{$p} );

        $filename = getcwd() . '/' . $d;
        print "$filename\n";

        system(
            'oowriter -invisible "macro:///Standard.Module1.ConvertWordToPDF('
              . $filename
              . ')"' );
    }
}

for ( ; ; ) {
    &main();
    sleep 10;
}