Search in sources :

Example 11 with FopFactory

use of org.apache.fop.apps.FopFactory in project OpenClinica by OpenClinica.

the class PdfProcessingFunction method run.

/*
     * The run() method.  Note that we will assume that all variables (i.e. file
     * paths) are set here.
     * 
     * Running this will open a file stream, perform a transform with the *.fo 
     * file (note, does not necessarily have to have a *.fo suffix) and then 
     * return a success/fail message.
     * (non-Javadoc)
     * @see org.akaza.openclinica.bean.service.ProcessingInterface#run()
     */
public ProcessingResultType run() {
    FopFactory fopFactory = FopFactory.newInstance();
    OutputStream out = null;
    File outputFile = null;
    String zipName = "_";
    File xslFile = null;
    try {
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        // set the renderer to be PDF
        // the expected sequence here will be xml -> xslt -> fo -> pdf
        // where fo is the transformed file
        File procExportDirectory;
        File[] oldFiles = null;
        if (this.getExportFileName() != null && this.getLocation() != null) {
            procExportDirectory = new File(this.getLocation());
            if (!procExportDirectory.isDirectory()) {
                procExportDirectory.mkdir();
            }
            outputFile = new File(procExportDirectory + File.separator + this.getExportFileName() + ".pdf");
            zipName = (procExportDirectory + File.separator + this.getExportFileName() + ".zip");
        } else {
            // getODMFILENAme is a path of .fo object
            outputFile = new File(this.getODMXMLFileName() + ".pdf");
            zipName = this.getODMXMLFileName() + ".zip";
        }
        // transformfilename is abs path+file name(.fo) transformFileName and odmxmlfile name are same?
        xslFile = new File(this.getTransformFileName());
        out = new FileOutputStream(outputFile);
        out = new BufferedOutputStream(out);
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
        TransformerFactory factory = TransformerFactory.newInstance();
        // identity transformer
        Transformer transformer = factory.newTransformer();
        Source src = new StreamSource(xslFile);
        // Resulting SAX events (the generated FO) must be piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());
        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);
        // Result processing
        FormattingResults foResults = fop.getResults();
        java.util.List pageSequences = foResults.getPageSequences();
        for (java.util.Iterator it = pageSequences.iterator(); it.hasNext(); ) {
            PageSequenceResults pageSequenceResults = (PageSequenceResults) it.next();
            logger.debug("PageSequence " + (String.valueOf(pageSequenceResults.getID()).length() > 0 ? pageSequenceResults.getID() : "<no id>") + " generated " + pageSequenceResults.getPageCount() + " pages.");
        }
        logger.debug("Generated " + foResults.getPageCount() + " pages in total.");
        out.close();
        if (isZip()) {
            if (outputFile != null) {
                ZipOutputStream zipOut = null;
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(outputFile);
                    zipOut = new ZipOutputStream(new FileOutputStream(new File(zipName)));
                    zipOut.putNextEntry(new ZipEntry(outputFile.getName()));
                    int bytesRead;
                    byte[] buff = new byte[512];
                    while ((bytesRead = fis.read(buff)) != -1) {
                        zipOut.write(buff, 0, bytesRead);
                    }
                    zipOut.closeEntry();
                    zipOut.finish();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (zipOut != null)
                        zipOut.close();
                    if (fis != null)
                        fis.close();
                }
            }
            setArchivedFileName(new File(zipName).getName());
        } else
            setArchivedFileName(outputFile.getName());
    } catch (Exception e) {
        e.printStackTrace();
        ProcessingResultType resultError = ProcessingResultType.FAIL;
        // view datasets page
        resultError.setUrl(CoreResources.getField("sysURL.base") + "ViewDatasets");
        resultError.setArchiveMessage("Failure thrown: " + e.getMessage());
        resultError.setDescription("Your job failed with the message of: " + e.getMessage());
        return resultError;
    } finally {
    }
    if (isDeleteOld()) {
        deleteOldFiles(this.getOldFiles(), outputFile, zipName);
    }
    if (isZip()) {
        outputFile.delete();
    }
    // delete intermediatory .fo file
    if (xslFile != null)
        xslFile.delete();
    // otherwise return a success with the URL link
    ProcessingResultType resultSuccess = ProcessingResultType.SUCCESS;
    resultSuccess.setUrl(CoreResources.getField("sysURL.base") + // to the pdf
    "AccessFile?fileId=");
    resultSuccess.setArchiveMessage("Success");
    resultSuccess.setDescription("Your job succeeded please find the URL below");
    return resultSuccess;
}
Also used : Transformer(javax.xml.transform.Transformer) FOUserAgent(org.apache.fop.apps.FOUserAgent) ZipOutputStream(java.util.zip.ZipOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ZipEntry(java.util.zip.ZipEntry) PageSequenceResults(org.apache.fop.apps.PageSequenceResults) FopFactory(org.apache.fop.apps.FopFactory) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) BufferedOutputStream(java.io.BufferedOutputStream) TransformerFactory(javax.xml.transform.TransformerFactory) Fop(org.apache.fop.apps.Fop) StreamSource(javax.xml.transform.stream.StreamSource) FormattingResults(org.apache.fop.apps.FormattingResults) FileInputStream(java.io.FileInputStream) FOPException(org.apache.fop.apps.FOPException) SAXResult(javax.xml.transform.sax.SAXResult) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 12 with FopFactory

use of org.apache.fop.apps.FopFactory in project series-rest-api by 52North.

the class PDFReportGenerator method encodeAndWriteTo.

@Override
public void encodeAndWriteTo(DataCollection<Data<QuantityValue>> data, OutputStream stream) throws IoHandlerException {
    try {
        generateOutput(data);
        DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
        Configuration cfg = cfgBuilder.build(document.newInputStream());
        URI baseURI = new File(".").toURI();
        FopFactory fopFactory = new FopFactoryBuilder(baseURI).setConfiguration(cfg).build();
        final String mimeType = Constants.APPLICATION_PDF;
        Fop fop = fopFactory.newFop(mimeType, stream);
        // FopFactory fopFactory = FopFactory.newInstance(cfg);
        // Fop fop = fopFactory.newFop(APPLICATION_PDF.getMimeType(), stream);
        // FopFactory fopFactory = fopFactoryBuilder.build();
        // Fop fop = fopFactory.newFop(APPLICATION_PDF.getMimeType(), stream);
        // Create PDF via XSLT transformation
        TransformerFactory transFact = TransformerFactory.newInstance();
        StreamSource transformationRule = getTransforamtionRule();
        Transformer transformer = transFact.newTransformer(transformationRule);
        Source source = new StreamSource(document.newInputStream());
        Result result = new SAXResult(fop.getDefaultHandler());
        if (LOGGER.isDebugEnabled()) {
            try {
                File tempFile = File.createTempFile(TEMP_FILE_PREFIX, ".xml");
                StreamResult debugResult = new StreamResult(tempFile);
                transformer.transform(source, debugResult);
                String xslResult = XmlObject.Factory.parse(tempFile).xmlText();
                LOGGER.debug("xsl-fo input (locale '{}'): {}", i18n.getTwoDigitsLanguageCode(), xslResult);
            } catch (IOException | TransformerException | XmlException e) {
                LOGGER.error("Could not debug XSL result output!", e);
            }
        }
        // XXX debug, diagram is not embedded
        transformer.transform(source, result);
    } catch (FOPException e) {
        throw new IoParseException("Failed to create Formatting Object Processor (FOP)", e);
    } catch (ConfigurationException e) {
        throw new IoParseException("Failed to read config for Formatting Object Processor (FOP)", e);
    } catch (TransformerConfigurationException e) {
        throw new IoParseException("Invalid transform configuration. Inspect xslt!", e);
    } catch (TransformerException e) {
        throw new IoParseException("Could not generate PDF report!", e);
    }
}
Also used : IoParseException(org.n52.io.IoParseException) DefaultConfigurationBuilder(org.apache.fop.configuration.DefaultConfigurationBuilder) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) Configuration(org.apache.fop.configuration.Configuration) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) Fop(org.apache.fop.apps.Fop) StreamSource(javax.xml.transform.stream.StreamSource) FopFactory(org.apache.fop.apps.FopFactory) IOException(java.io.IOException) URI(java.net.URI) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) FopFactoryBuilder(org.apache.fop.apps.FopFactoryBuilder) FOPException(org.apache.fop.apps.FOPException) SAXResult(javax.xml.transform.sax.SAXResult) ConfigurationException(org.apache.fop.configuration.ConfigurationException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) XmlException(org.apache.xmlbeans.XmlException) File(java.io.File) TransformerException(javax.xml.transform.TransformerException)

Example 13 with FopFactory

use of org.apache.fop.apps.FopFactory in project tutorials by eugenp.

the class ApacheFOPConvertHTMLIntegrationTest method fromFODocumentToPDF.

private void fromFODocumentToPDF(final Document fo, final String outputFile) throws Exception {
    final FopFactory fopFactory = FopFactory.newInstance();
    final OutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(outputFile)));
    final Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outStream);
    final TransformerFactory factory = TransformerFactory.newInstance();
    final Transformer transformer = factory.newTransformer();
    final DOMSource src = new DOMSource(fo);
    final Result res = new SAXResult(fop.getDefaultHandler());
    transformer.transform(src, res);
    outStream.close();
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) SAXResult(javax.xml.transform.sax.SAXResult) Fop(org.apache.fop.apps.Fop) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) FopFactory(org.apache.fop.apps.FopFactory) BufferedOutputStream(java.io.BufferedOutputStream) File(java.io.File) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) DOMResult(javax.xml.transform.dom.DOMResult)

Example 14 with FopFactory

use of org.apache.fop.apps.FopFactory in project tutorials by eugenp.

the class ApacheFOPHeroldLiveTest method fromFODocumentToPDF.

private void fromFODocumentToPDF(final Document fo, final String outputFile) throws Exception {
    final FopFactory fopFactory = FopFactory.newInstance();
    final OutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(outputFile)));
    final Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outStream);
    final TransformerFactory factory = TransformerFactory.newInstance();
    final Transformer transformer = factory.newTransformer();
    final DOMSource src = new DOMSource(fo);
    final Result res = new SAXResult(fop.getDefaultHandler());
    transformer.transform(src, res);
    outStream.close();
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) SAXResult(javax.xml.transform.sax.SAXResult) Fop(org.apache.fop.apps.Fop) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) FopFactory(org.apache.fop.apps.FopFactory) BufferedOutputStream(java.io.BufferedOutputStream) File(java.io.File) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) DOMResult(javax.xml.transform.dom.DOMResult)

Aggregations

FopFactory (org.apache.fop.apps.FopFactory)14 Fop (org.apache.fop.apps.Fop)11 Transformer (javax.xml.transform.Transformer)9 TransformerFactory (javax.xml.transform.TransformerFactory)9 SAXResult (javax.xml.transform.sax.SAXResult)9 Result (javax.xml.transform.Result)8 StreamSource (javax.xml.transform.stream.StreamSource)8 File (java.io.File)7 Source (javax.xml.transform.Source)6 BufferedOutputStream (java.io.BufferedOutputStream)5 FileOutputStream (java.io.FileOutputStream)5 IOException (java.io.IOException)5 OutputStream (java.io.OutputStream)5 FOPException (org.apache.fop.apps.FOPException)4 FOUserAgent (org.apache.fop.apps.FOUserAgent)4 URI (java.net.URI)3 DOMResult (javax.xml.transform.dom.DOMResult)3 DOMSource (javax.xml.transform.dom.DOMSource)3 StreamResult (javax.xml.transform.stream.StreamResult)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2