Search in sources :

Example 1 with FopFactory

use of org.apache.fop.apps.FopFactory in project opennms by OpenNMS.

the class OnmsPdfViewResolver method resolveView.

@Override
public void resolveView(ServletRequest request, ServletResponse response, Preferences preferences, Object viewData) throws Exception {
    InputStream is = new ByteArrayInputStream(((String) viewData).getBytes(StandardCharsets.UTF_8));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    FopFactory fopFactory = FopFactory.newInstance();
    fopFactory.setStrictValidation(false);
    FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
    TransformerFactory tfact = TransformerFactory.newInstance();
    Transformer transformer = tfact.newTransformer();
    Source src = new StreamSource(is);
    Result res = new SAXResult(fop.getDefaultHandler());
    transformer.transform(src, res);
    byte[] contents = out.toByteArray();
    response.setContentLength(contents.length);
    response.getOutputStream().write(contents);
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) FOUserAgent(org.apache.fop.apps.FOUserAgent) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Fop(org.apache.fop.apps.Fop) StreamSource(javax.xml.transform.stream.StreamSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) 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) SAXResult(javax.xml.transform.sax.SAXResult) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 2 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<QuantityData> data, OutputStream stream) throws IoParseException {
    try {
        generateOutput(data);
        DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
        Configuration cfg = cfgBuilder.build(document.newInputStream());
        FopFactory fopFactory = new FopFactoryBuilder(baseURI).setConfiguration(cfg).build();
        final String mimeType = MimeType.APPLICATION_PDF.getMimeType();
        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 (SAXException | ConfigurationException | IOException 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.avalon.framework.configuration.DefaultConfigurationBuilder) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) Configuration(org.apache.avalon.framework.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) 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) SAXException(org.xml.sax.SAXException) FopFactoryBuilder(org.apache.fop.apps.FopFactoryBuilder) FOPException(org.apache.fop.apps.FOPException) SAXResult(javax.xml.transform.sax.SAXResult) ConfigurationException(org.apache.avalon.framework.configuration.ConfigurationException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) XmlException(org.apache.xmlbeans.XmlException) File(java.io.File) TransformerException(javax.xml.transform.TransformerException)

Example 3 with FopFactory

use of org.apache.fop.apps.FopFactory in project opennms by OpenNMS.

the class PDFReportRenderer method render.

/**
 * <p>render</p>
 *
 * @param in a {@link java.io.Reader} object.
 * @param out a {@link java.io.OutputStream} object.
 * @param xslt a {@link java.io.Reader} object.
 * @throws org.opennms.reporting.availability.render.ReportRenderException if any.
 */
public void render(final Reader in, final OutputStream out, final Reader xslt) throws ReportRenderException {
    try {
        final FopFactory fopFactory = FopFactory.newInstance();
        fopFactory.setStrictValidation(false);
        final Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
        final TransformerFactory tfact = TransformerFactory.newInstance();
        final Transformer transformer = tfact.newTransformer(new StreamSource(xslt));
        transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
        final StreamSource streamSource = new StreamSource(in);
        transformer.transform(streamSource, new SAXResult(fop.getDefaultHandler()));
    } catch (final Exception e) {
        throw new ReportRenderException(e);
    }
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) SAXResult(javax.xml.transform.sax.SAXResult) Fop(org.apache.fop.apps.Fop) StreamSource(javax.xml.transform.stream.StreamSource) FopFactory(org.apache.fop.apps.FopFactory)

Example 4 with FopFactory

use of org.apache.fop.apps.FopFactory in project wildfly-camel by wildfly-extras.

the class FopIntegrationTest method testFopComponentWithCustomFactory.

@Test
public void testFopComponentWithCustomFactory() throws Exception {
    FopFactory fopFactory = FopFactory.newInstance(new URI("/"), FopIntegrationTest.class.getResourceAsStream("/factory.xml"));
    initialContext.bind("fopFactory", fopFactory);
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("direct:start").to("xslt:template.xsl").setHeader("foo", constant("bar")).to("fop:pdf?fopFactory=#fopFactory").setHeader(Exchange.FILE_NAME, constant("resultB.pdf")).to("file:{{jboss.server.data.dir}}/fop").to("mock:result");
        }
    });
    MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
    mockEndpoint.expectedMessageCount(1);
    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        template.sendBody("direct:start", FopIntegrationTest.class.getResourceAsStream("/data.xml"));
        mockEndpoint.assertIsSatisfied();
        String dataDir = System.getProperty("jboss.server.data.dir");
        PDDocument document = PDDocument.load(Paths.get(dataDir, "fop", "resultB.pdf").toFile());
        String pdfText = extractTextFromDocument(document);
        Assert.assertTrue(pdfText.contains("Project"));
        Assert.assertTrue(pdfText.contains("John Doe"));
    } finally {
        camelctx.stop();
        initialContext.unbind("fopFactory");
    }
}
Also used : DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) CamelContext(org.apache.camel.CamelContext) ProducerTemplate(org.apache.camel.ProducerTemplate) RouteBuilder(org.apache.camel.builder.RouteBuilder) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) PDDocument(org.apache.pdfbox.pdmodel.PDDocument) FopFactory(org.apache.fop.apps.FopFactory) URI(java.net.URI) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) IOException(java.io.IOException) Test(org.junit.Test)

Example 5 with FopFactory

use of org.apache.fop.apps.FopFactory in project grafikon by jub77.

the class DrawOutput method processPdf.

private void processPdf(Collection<Image> images, OutputStream stream, DrawLayout layout) throws OutputException {
    PDFDocumentGraphics2D g2d;
    try {
        g2d = new PDFDocumentGraphics2D();
        g2d.setGraphicContext(new GraphicContext());
        FopFactory fopFactory = PdfTransformer.createFopFactory();
        FOUserAgent userAgent = fopFactory.newFOUserAgent();
        FontConfig fc = userAgent.getRendererConfig(MimeConstants.MIME_PDF, new PDFRendererConfigParser()).getFontInfoConfig();
        FontManager fontManager = fopFactory.getFontManager();
        DefaultFontConfigurator fontInfoConfigurator = new DefaultFontConfigurator(fontManager, null, false);
        List<EmbedFontInfo> fontInfoList = fontInfoConfigurator.configure(fc);
        FontInfo fontInfo = new FontInfo();
        FontSetup.setup(fontInfo, fontInfoList, userAgent.getResourceResolver(), fontManager.isBase14KerningEnabled());
        g2d.setFontInfo(fontInfo);
        g2d.setFont(new Font("SansCondensed", Font.PLAIN, g2d.getFont().getSize()));
        List<Dimension> sizes = this.getSizes(images, g2d);
        Dimension size = this.getTotalSize(sizes, layout);
        g2d.setupDocument(stream, size.width, size.height);
        this.drawImages(sizes, images, g2d, layout);
        g2d.finish();
    } catch (IOException | FOPException e) {
        throw new OutputException(e.getMessage(), e);
    }
}
Also used : EmbedFontInfo(org.apache.fop.fonts.EmbedFontInfo) GraphicContext(org.apache.xmlgraphics.java2d.GraphicContext) PDFRendererConfigParser(org.apache.fop.render.pdf.PDFRendererConfig.PDFRendererConfigParser) FOUserAgent(org.apache.fop.apps.FOUserAgent) FontConfig(org.apache.fop.fonts.FontConfig) PDFDocumentGraphics2D(org.apache.fop.svg.PDFDocumentGraphics2D) FopFactory(org.apache.fop.apps.FopFactory) Dimension(java.awt.Dimension) IOException(java.io.IOException) FontManager(org.apache.fop.fonts.FontManager) Font(java.awt.Font) FOPException(org.apache.fop.apps.FOPException) OutputException(net.parostroj.timetable.output2.OutputException) EmbedFontInfo(org.apache.fop.fonts.EmbedFontInfo) FontInfo(org.apache.fop.fonts.FontInfo) DefaultFontConfigurator(org.apache.fop.fonts.DefaultFontConfigurator)

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