Sunday, December 2, 2007

Getting started with iText - Part 1 (HelloWorld.java)

Sheerly out of boredom I decided to translate some of the iText examples to ColdFusion. Obviously much of the need for iText was eliminated with the introduction of CFDOCUMENT (MX7) and CFPDF (ColdFusion 8). But I think it will be a good learning exercise if nothing else. Bear in mind I tried to keep the code as close as possible to the original java examples


Now where else would I begin but with a "Hello World" example ;)

Source: http://itextdocs.lowagie.com/tutorial/general/
Documentation: Creating a document in 5 steps
Example: HelloWorld.java


<h1>Generates a simple 'Hello World' PDF file</h1>
<cfscript>
    savedErrorMessage = "";

    // by default outputs to current directory. change as needed
    fullPathToOutputFile = ExpandPath("./HelloWorld.pdf");

    // step 1: creation of a document-object
    document = createObject("java", "com.lowagie.text.Document").init();

    try {
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        outStream = createObject("java", "java.io.FileOutputStream").init(fullPathToOutputFile);
        writer = createObject("java", "com.lowagie.text.pdf.PdfWriter").getInstance(document, outStream);

        // step 3: we open the document
        document.open();

        // step 4: we add a paragraph to the document
        paragraph = createObject("java", "com.lowagie.text.Paragraph").init("Hello World");
        document.add(paragraph);

        WriteOutput("Finished!");
    }
    catch (com.lowagie.text.DocumentException de) {
        savedErrorMessage = de;
    }
    catch (java.io.IOException ioe) {
        savedErrorMessage = ioe;
    }

    // step 5: we close the document
    document.close();
    // close the output stream
    outStream.close();

</cfscript>

<!--- show any errors --->
<cfif len(savedErrorMessage) gt 0>
    Error - unable to create document
    <cfdump var="#savedErrorMessage#">
</cfif>

0 comments:

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Header image adapted from atomicjeep