Thursday 24 October 2013

Generate PDF files in webMethods

If your application needs to generate PDF documents dynamically, you need the Apache FOP library. The open source FOP library makes PDF creation a snap. This article gives a step-by-step guide to using it to generate PDF documents from webMethods.
 
  1. Download FOP library and upload to common lib directory on Integration Server. FOP library can be download from Apache FOP site.
  2. Create an IS document. The IS document is the container for all the elements of a PDF document.
  3. Invoke webMethods built-in service pub.xml:documentToXMLString, to convert IS document (IData object) to an XML string.
  4. Create a XSLT service. The XSLT service performs transformation of XML string to XSL-FO (a variant of XSL). It can also do input XML validation. Details of XSL-FO can be found at http://www.w3schools.com/xslfo/.
  5. Create a Java service to invoke FOP processor.

  Diagram below shows how it works.



XSLT processor in the diagram is the IS XSLT service that creates an XML containing formatting objects by taking data from the first XML. This resultant XML is de-serialized into Java objects. IS jave service de-serializes resultant XML into Java objects, invoke FOP processor to creates a PDF file using these Java objects.

Code snippet for Java Service:

IDataCursor idc = pipeline.getCursor();
String inputXSLFO = IDataUtil.getString( idc, "inputXSLFO" );

try {
            FopFactory fopFactory = FopFactory.newInstance();
           
            // a user agent is needed for transformation
            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            // to store output
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();

            FOP fop = fopFactory.newFop
                                    (MimeConstants.MIME_PDF, foUserAgent, outStream);
            // Resulting SAX events (the generated FO)
            // must be piped through to FOP
            Result res = new SAXResult(fop.getDefaultHandler());

            // Setup input for XSLT transformation
            InputStream xmlStream = (InputStream) (new ByteArrayInputStream(inputXSLFO.getBytes())) ;
            Source src = new StreamSource(xmlStream, "UTF-16");

            transformer.transform(src, res);
            xmlStream.close();

            idc.insertAfter("outputPDFByteArray", outStream.toByteArray() );
            idc.destroy();
            outStream.close();

}
catch (Exception e){     
            idc.insertAfter("outputPDFByteArray", null);
}
 

No comments:

Post a Comment