org.apache.fop.apps.FopFactory Java Examples

The following examples show how to use org.apache.fop.apps.FopFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApacheFopWorker.java    From scipio-erp with Apache License 2.0 7 votes vote down vote up
/** Returns a new Fop instance. Note: FOP documentation recommends using
 * a Fop instance for one transform run only.
 * @param out The target (result) OutputStream instance
 * @param outputFormat Optional output format, defaults to "application/pdf"
 * @param foUserAgent FOUserAgent object which may contains encryption-params in render options
 * @return Fop instance
 */
public static Fop createFopInstance(OutputStream out, String outputFormat, FOUserAgent foUserAgent) throws FOPException {
    if (UtilValidate.isEmpty(outputFormat)) {
        outputFormat = MimeConstants.MIME_PDF;
    }
    if (UtilValidate.isEmpty(foUserAgent)) {
        FopFactory fopFactory = getFactoryInstance();
        foUserAgent = fopFactory.newFOUserAgent();
    }
    Fop fop;
    if (out != null) {
        fop = fopFactory.newFop(outputFormat, foUserAgent, out);
    } else {
        fop = fopFactory.newFop(outputFormat, foUserAgent);
    }
    return fop;
}
 
Example #2
Source File: FORendererApacheFOP.java    From docx4j-export-FO with Apache License 2.0 6 votes vote down vote up
protected void render(FopFactory fopFactory, FOUserAgent foUserAgent, String outputFormat, Source foDocumentSrc, PlaceholderReplacementHandler.PlaceholderLookup placeholderLookup, OutputStream outputStream) throws Docx4JException {
	Fop fop = null;
	Result result = null;
	try {
		if (foUserAgent==null) {
			fop = fopFactory.newFop(outputFormat, outputStream);
		} else {
			fop = fopFactory.newFop(outputFormat, foUserAgent, outputStream);				
		}
		result = (placeholderLookup == null ?
				//1 Pass
				new SAXResult(fop.getDefaultHandler()) :
				//2 Pass
				new SAXResult(new PlaceholderReplacementHandler(fop.getDefaultHandler(), placeholderLookup)));
	} catch (FOPException e) {
		throw new Docx4JException("Exception setting up result for fo transformation: " + e.getMessage(), e);
	}
	
	XmlSerializerUtil.serialize(foDocumentSrc, result, false, false);
}
 
Example #3
Source File: FORendererApacheFOP.java    From docx4j-export-FO with Apache License 2.0 6 votes vote down vote up
protected  static FopFactory getFopFactory(String userConfig) throws FOPException {

		//The current implementation doesn't pass the user config to the fop factory 
		//if there is only a factory per Thread, all documents rendered in that  
		//Thread would use the configuration done for the first document.
		//For this reason disable the reuse of the FopFactories until this issue 
		//gets resolved.
		return createFopFactory(userConfig);
//		FopFactory fopFactory = fopFactories.get(Thread.currentThread().getId());
//		if (fopFactory == null) {
//			synchronized(fopFactories) {
//				fopFactory = createFopFactory(userConfig);
//				fopFactories.put(Thread.currentThread().getId(), fopFactory);
//			}
//		}
//		fopFactory.setUserConfig(userConfig);
//		return fopFactory;
	}
 
Example #4
Source File: DocuTest.java    From Digital with GNU General Public License v3.0 6 votes vote down vote up
private void startFOP(FopFactory fopFactory, File xslfo, File pdfOut) throws IOException, TransformerException, FOPException {
    try (OutputStream out = new BufferedOutputStream(new FileOutputStream(pdfOut))) {
        // Step 3: Construct fop with desired output format
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

        // Step 4: Setup JAXP using identity transformer
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(); // identity transformer

        // Step 5: Setup input and output for XSLT transformation
        // Setup input stream
        Source src = new StreamSource(xslfo);

        // Resulting SAX events (the generated FO) must be piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        // Step 6: Start XSLT transformation and FOP processing
        transformer.transform(src, res);

    }
}
 
Example #5
Source File: ApacheFopWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/** Returns an instance of the FopFactory class. FOP documentation recommends
 * the reuse of the factory instance because of the startup time.
 * @return FopFactory The FopFactory instance
 */
public static FopFactory getFactoryInstance() {
    if (fopFactory == null) {
        synchronized (ApacheFopWorker.class) {
            if (fopFactory != null) {
                return fopFactory;
            }

            try {
                URL configFilePath = FlexibleLocation.resolveLocation(fopPath + "/fop.xconf");
                File userConfigFile = FileUtil.getFile(configFilePath.getFile());
                if (userConfigFile.exists()) {
                    fopFactory = FopFactory.newInstance(userConfigFile);
                } else {
                    Debug.logWarning("FOP configuration file not found: " + userConfigFile, module);
                }
                URL fontBaseFileUrl = FlexibleLocation.resolveLocation(fopFontBaseProperty);
                File fontBaseFile = FileUtil.getFile(fontBaseFileUrl.getFile());

                if (fontBaseFile.isDirectory()) {
                    fopFactory.getFontManager().setResourceResolver(ResourceResolverFactory.createDefaultInternalResourceResolver(fontBaseFile.toURI()));
                } else {
                    Debug.logWarning("FOP font base URL not found: " + fontBaseFile, module);
                }
                Debug.logInfo("FOP FontBaseURL: " + fopFactory.getFontManager().getResourceResolver().getBaseURI(), module);
            } catch (Exception e) {
                Debug.logWarning(e, "Error reading FOP configuration: ", module);
            }
        }
    }
    return fopFactory;
}
 
Example #6
Source File: FORendererApacheFOP.java    From docx4j-export-FO with Apache License 2.0 5 votes vote down vote up
/**
 * Allow user access to FOUserAgent, so they can setAccessibility(true).  Access to other settings
 * is possible but unsupported.
 * 
 * @param wmlPackage
 * @return
 * @throws FOPException
 */
public static FOUserAgent getFOUserAgent(FOSettings settings) throws Docx4JException, FOPException {
	
	FopFactory fopFactory = getFopFactory(
			setupApacheFopConfiguration(settings)); // relies on the WordML package being there, for font info
	settings.getSettings().put(FOP_FACTORY, fopFactory);
	
    FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
	settings.getSettings().put(FO_USER_AGENT, foUserAgent);
	
	return foUserAgent;
}
 
Example #7
Source File: DocuTest.java    From Digital with GNU General Public License v3.0 5 votes vote down vote up
public void testDocu() throws IOException, NodeException, PinException, TransformerException, SAXException {
    FopFactory fopFactory = FopFactory.newInstance(new File(Resources.getRoot(), "docu/fop.xconf"));

    File maven = Resources.getRoot().getParentFile().getParentFile().getParentFile();
    File target = new File(maven, "target/docu");
    File target2 = new File(maven, "target/docuDist");

    File images = new File(target, "img");
    images.mkdirs();
    target2.mkdirs();

    final File library = new File(target, "library.xml");
    write74xx(library);

    for (Language l : Lang.getBundle().getSupportedLanguages()) {
        // set language
        Lang.setActualRuntimeLanguage(l);
        final String basename = "Documentation_" + l.getName();
        // write xml
        File xml = new File(target, basename + ".xml");
        try (Writer w = new OutputStreamWriter(new FileOutputStream(xml), StandardCharsets.UTF_8)) {
            writeXML(w, images, l.getName(), library);
        }

        // start xslt transformation
        File xslFO = new File(target, basename + ".fo");
        File xslt = new File(Resources.getRoot(), "docu/elem2fo.xslt");
        startXalan(xml, xslt, xslFO);

        // write pdf
        File pdf = new File(target, basename + ".pdf");
        startFOP(fopFactory, xslFO, pdf);

        copy(pdf, new File(target2, "Doc_" + l.getFileName() + ".pdf"));
    }
}
 
Example #8
Source File: RendererManagerFopTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that a FOP file is valid and transform it into pdf file.
 * @param fopFile the fop content
 * @param pdffile the output
 * @return true if it is valid, false otherwise
 * @throws Exception
 */
private boolean validateFop2pdf( File fopFile, File pdffile ) throws Exception {

	InputStream conf = FopRenderer.class.getResourceAsStream( "/fop.xconf" );
	File fopConfig = new File( this.outputDir, "fop.xconf" );
	Utils.copyStream( conf, fopConfig );

	OutputStream out = null;
	try {
			out = new BufferedOutputStream(new FileOutputStream(pdffile));
			FopFactory fopFactory = FopFactory.newInstance(fopConfig);
			Fop fop =  fopFactory.newFop("application/pdf", out);
			Source src = new StreamSource( fopFile );

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

			Result res = new SAXResult(fop.getDefaultHandler());
			transformer.transform(src, res);

	} finally {
			Utils.closeQuietly ( out );
	}

	return pdffile.length() > 0;

}
 
Example #9
Source File: FopIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@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(new JndiBeanRepository());
    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.close();
        initialContext.unbind("fopFactory");
    }
}
 
Example #10
Source File: FORendererApacheFOP.java    From docx4j-export-FO with Apache License 2.0 4 votes vote down vote up
protected Fop createFop(String userConfiguration, String outputFormat, OutputStream outputStream) throws FOPException {
	
	FopFactory fopFactory = getFopFactory(userConfiguration);
	return fopFactory.newFop(outputFormat != null ? outputFormat : MimeConstants.MIME_PDF, outputStream);
}
 
Example #11
Source File: FopTask.java    From pcgen with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static FopFactory getFactory()
{
	return FOP_FACTORY;
}
 
Example #12
Source File: SiteInfoToolServlet.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Takes a DOM structure and renders a PDF
 * 
 * @param doc
 *        DOM structure
 * @param streamOut
 */
@SuppressWarnings("unchecked")
protected void generatePDF(Document doc, OutputStream streamOut)
{
	String xslFileName = "participants-all-attrs.xsl";
	Locale currentLocale = rb.getLocale();
	if (currentLocale!=null){
		String fullLocale = currentLocale.toString();
		xslFileName = "participants-all-attrs_" + fullLocale + ".xsl";
		InputStream inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName);
		if (inputStream == null){
			xslFileName = "participants-all-attrs_" + currentLocale.getCountry() + ".xsl";
			inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName);
			if (inputStream == null){
				//We use the default file
				xslFileName = "participants-all-attrs.xsl";
			}
		}

		IOUtils.closeQuietly(inputStream);
	}
	String configFileName = "userconfig.xml";
	DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
	InputStream configInputStream = null;
	try 
	{
		configInputStream = getClass().getClassLoader().getResourceAsStream(configFileName);
		Configuration cfg = cfgBuilder.build(configInputStream);
		
		FopFactory fopFactory = FopFactory.newInstance();
		fopFactory.setUserConfig(cfg);
		fopFactory.setStrictValidation(false);
		FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
		if (!StringUtils.isEmpty(ServerConfigurationService.getString("pdf.default.font"))) {
		    // this allows font substitution to support i18n chars in PDFs - SAK-21909
		    FontQualifier fromQualifier = new FontQualifier();
		    fromQualifier.setFontFamily("DEFAULT_FONT");
		    FontQualifier toQualifier = new FontQualifier();
		    toQualifier.setFontFamily(ServerConfigurationService.getString("pdf.default.font", "Helvetica"));
		    FontSubstitutions result = new FontSubstitutions();
		    result.add(new FontSubstitution(fromQualifier, toQualifier));
		    fopFactory.getFontManager().setFontSubstitutions(result);
		}
		Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, streamOut);
		InputStream in = getClass().getClassLoader().getResourceAsStream(xslFileName);
		Transformer transformer = transformerFactory.newTransformer(new StreamSource(in));
		transformer.setParameter("titleName", rb.getString("sitegen.siteinfolist.title.name"));
		transformer.setParameter("titleId", rb.getString("sitegen.siteinfolist.title.id"));
		transformer.setParameter("titleSection", rb.getString("sitegen.siteinfolist.title.section"));
		transformer.setParameter("titleCredit", rb.getString("sitegen.siteinfolist.title.credit"));
		transformer.setParameter("titleRole", rb.getString("sitegen.siteinfolist.title.role"));
		transformer.setParameter("titleStatus", rb.getString("sitegen.siteinfolist.title.status"));

		Source src = new DOMSource(doc);
		transformer.transform(src, new SAXResult(fop.getDefaultHandler()));
	}
	catch (Exception e)
	{
		log.warn("{}.generatePDF(): {}", this, e.toString());
	}
	finally
	{
		IOUtils.closeQuietly(configInputStream);
	}
}
 
Example #13
Source File: FopTask.java    From pcgen with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static FopFactory getFactory()
{
	return FOP_FACTORY;
}
 
Example #14
Source File: PdfRenderer.java    From roboconf-platform with Apache License 2.0 4 votes vote down vote up
@Override
protected File writeFileContent( String fileContent ) throws IOException {

	// Generate FOP rendering
	new RenderingManager().render(
			this.outputDirectory,
			this.applicationTemplate,
			this.applicationDirectory,
			Renderer.FOP,
			this.options,
			this.typeAnnotations );

	File index_fo = new File( this.outputDirectory, "index.fo" );
	File index_pdf = new File( this.outputDirectory, "index.pdf" );

	// Copy the FOP configuration file in outputDirectory
	InputStream conf = getClass().getResourceAsStream( "/fop.xconf" );
	File fopConfig = new File( this.outputDirectory, "fop.xconf" );
	Utils.copyStream( conf, fopConfig );

	// Generate the PDF rendering
	OutputStream out = null;
	try {
		out = new BufferedOutputStream( new FileOutputStream(index_pdf) );
		FopFactory fopFactory = FopFactory.newInstance( fopConfig );
		Fop fop =  fopFactory.newFop( "application/pdf", out );
		Source src = new StreamSource( index_fo );

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

		Result res = new SAXResult(fop.getDefaultHandler());
		transformer.transform(src, res);

	} catch ( Exception e) {
		throw new IOException( e );

	} finally {
		Utils.closeQuietly ( out );
	}

	return index_pdf;
}
 
Example #15
Source File: SiteInfoToolServlet.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Takes a DOM structure and renders a PDF
 * 
 * @param doc
 *        DOM structure
 * @param streamOut
 */
@SuppressWarnings("unchecked")
protected void generatePDF(Document doc, OutputStream streamOut)
{
	String xslFileName = "participants-all-attrs.xsl";
	Locale currentLocale = rb.getLocale();
	if (currentLocale!=null){
		String fullLocale = currentLocale.toString();
		xslFileName = "participants-all-attrs_" + fullLocale + ".xsl";
		InputStream inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName);
		if (inputStream == null){
			xslFileName = "participants-all-attrs_" + currentLocale.getCountry() + ".xsl";
			inputStream = getClass().getClassLoader().getResourceAsStream(xslFileName);
			if (inputStream == null){
				//We use the default file
				xslFileName = "participants-all-attrs.xsl";
			}
		}

		IOUtils.closeQuietly(inputStream);
	}
	String configFileName = "userconfig.xml";
	DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
	InputStream configInputStream = null;
	try 
	{
		configInputStream = getClass().getClassLoader().getResourceAsStream(configFileName);
		Configuration cfg = cfgBuilder.build(configInputStream);
		
		FopFactory fopFactory = FopFactory.newInstance();
		fopFactory.setUserConfig(cfg);
		fopFactory.setStrictValidation(false);
		FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
		if (!StringUtils.isEmpty(ServerConfigurationService.getString("pdf.default.font"))) {
		    // this allows font substitution to support i18n chars in PDFs - SAK-21909
		    FontQualifier fromQualifier = new FontQualifier();
		    fromQualifier.setFontFamily("DEFAULT_FONT");
		    FontQualifier toQualifier = new FontQualifier();
		    toQualifier.setFontFamily(ServerConfigurationService.getString("pdf.default.font", "Helvetica"));
		    FontSubstitutions result = new FontSubstitutions();
		    result.add(new FontSubstitution(fromQualifier, toQualifier));
		    fopFactory.getFontManager().setFontSubstitutions(result);
		}
		Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, streamOut);
		InputStream in = getClass().getClassLoader().getResourceAsStream(xslFileName);
		Transformer transformer = transformerFactory.newTransformer(new StreamSource(in));
		transformer.setParameter("titleName", rb.getString("sitegen.siteinfolist.title.name"));
		transformer.setParameter("titleId", rb.getString("sitegen.siteinfolist.title.id"));
		transformer.setParameter("titleSection", rb.getString("sitegen.siteinfolist.title.section"));
		transformer.setParameter("titleCredit", rb.getString("sitegen.siteinfolist.title.credit"));
		transformer.setParameter("titleRole", rb.getString("sitegen.siteinfolist.title.role"));
		transformer.setParameter("titleStatus", rb.getString("sitegen.siteinfolist.title.status"));

		Source src = new DOMSource(doc);
		transformer.transform(src, new SAXResult(fop.getDefaultHandler()));
	}
	catch (Exception e)
	{
		log.warn("{}.generatePDF(): {}", this, e.toString());
	}
	finally
	{
		IOUtils.closeQuietly(configInputStream);
	}
}
 
Example #16
Source File: PdfBookConverter.java    From AsciidocFX with Apache License 2.0 4 votes vote down vote up
@Override
public void convert(boolean askPath, Consumer<String>... nextStep) {

    final Path currentTabPath = current.currentPath().get();
    final Path currentTabPathDir = currentTabPath.getParent();
    final Path configPath = asciiDocController.getConfigPath();

    threadService.runActionLater(() -> {

        final Path pdfPath = directoryService.getSaveOutputPath(ExtensionFilters.PDF, askPath);

        docBookConverter.convert(false, docbook -> {

            indikatorService.startProgressBar();
            logger.debug("PDF conversion started");

            final Path docbookTempfile = IOHelper.createTempFile(currentTabPathDir, ".xml");
            IOHelper.writeToFile(docbookTempfile, docbook, CREATE, WRITE, TRUNCATE_EXISTING);

            try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(pdfPath.toFile()));) {
                // Setup XSLT
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer(new StreamSource(configPath.resolve("docbook-config/fo-pdf.xsl").toFile()));
                transformer.setParameter("highlight.xslthl.config", configPath.resolve("docbook-config/xslthl-config.xml").toUri().toASCIIString());
                transformer.setParameter("admon.graphics.path", configPath.resolve("docbook/images/").toUri().toASCIIString());
                transformer.setParameter("callout.graphics.path", configPath.resolve("docbook/images/callouts/").toUri().toASCIIString());

                if (Objects.isNull(fopFactory)) {
                    fopFactory = FopFactory.newInstance(configPath.resolve("docbook-config/fop.xconf.xml").toFile());
                }

                Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outputStream);

                // Setup input for XSLT transformation
                Source src = new StreamSource(docbookTempfile.toFile());

                // Resulting SAX events (the generated FO) must be piped through to FOP
                Result res = new SAXResult(fop.getDefaultHandler());

                // Step 6: Start XSLT transformation and FOP processing
                transformer.transform(src, res);

                Files.deleteIfExists(docbookTempfile);

                // Result processing
                FormattingResults foResults = fop.getResults();

                logger.info("Generated {} pages in total.", foResults.getPageCount());

            } catch (Exception e) {
                logger.error("Problem occured while converting to PDF", e);
            } finally {
                indikatorService.stopProgressBar();
                logger.debug("PDF conversion ended");

                asciiDocController.addRemoveRecentList(pdfPath);
            }
        });
    });

}