org.apache.fop.apps.Fop Java Examples

The following examples show how to use org.apache.fop.apps.Fop. 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: ApacheFopWorker.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/** Transform an xsl-fo StreamSource to the specified output format.
 * @param src The xsl-fo StreamSource instance
 * @param stylesheet Optional stylesheet StreamSource instance
 * @param fop
 */
public static void transform(StreamSource src, StreamSource stylesheet, Fop fop) throws FOPException {
    Result res = new SAXResult(fop.getDefaultHandler());
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;
        if (stylesheet == null) {
            transformer = factory.newTransformer();
        } else {
            transformer = factory.newTransformer(stylesheet);
        }
        transformer.setURIResolver(new LocalResolver(transformer.getURIResolver()));
        transformer.transform(src, res);
    } catch (Exception e) {
        throw new FOPException(e);
    }
}
 
Example #3
Source File: PDFGenerationTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void createAndValidate(String filename) throws Exception {
	SimpleReportFacade facade = SimpleReportFacade.newFacade();

	File file = new File("src/test/resources/" + filename);
	XmlSimpleReport simpleReport = facade.unmarshall(file);

	try (FileOutputStream fos = new FileOutputStream("target/report.pdf")) {
		Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, fos);
		Result result = new SAXResult(fop.getDefaultHandler());
		facade.generatePdfReport(simpleReport, result);
	}
	
	File pdfReport = new File("target/report.pdf");
	assertTrue(pdfReport.exists());
	assertTrue(pdfReport.delete(), "Cannot delete PDF document (IO error)");
	assertFalse(pdfReport.exists());
}
 
Example #4
Source File: MCRFoFormatterFOP.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void transform(MCRContent input, OutputStream out) throws TransformerException, IOException {
    try {
        final FOUserAgent userAgent = fopFactory.newFOUserAgent();
        userAgent.setProducer(new MessageFormat("MyCoRe {0} ({1})", Locale.ROOT)
            .format(new Object[] { MCRCoreVersion.getCompleteVersion(), userAgent.getProducer() }));

        final Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out);
        final Source src = input.getSource();
        final Result res = new SAXResult(fop.getDefaultHandler());
        Transformer transformer = getTransformerFactory().newTransformer();
        transformer.transform(src, res);
    } catch (FOPException e) {
        throw new TransformerException(e);
    } finally {
        out.close();
    }
}
 
Example #5
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 #6
Source File: PDFGenerationTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void createAndValidate(String filename) throws Exception {
	DetailedReportFacade facade = DetailedReportFacade.newFacade();

	File file = new File("src/test/resources/" + filename);
	XmlDetailedReport detailedReport = facade.unmarshall(file);

	try (FileOutputStream fos = new FileOutputStream("target/report.pdf")) {

		Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, fos);
		Result result = new SAXResult(fop.getDefaultHandler());
		facade.generatePdfReport(detailedReport, result);
	}
	
	File pdfReport = new File("target/report.pdf");
	assertTrue(pdfReport.exists());
	assertTrue(pdfReport.delete(), "Cannot delete PDF document (IO error)");
	assertFalse(pdfReport.exists());
	
}
 
Example #7
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 #8
Source File: PDFGenerationTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void createAndValidate(String filename) throws Exception {
	SimpleCertificateReportFacade facade = SimpleCertificateReportFacade.newFacade();

	File file = new File("src/test/resources/" + filename);
	XmlSimpleCertificateReport simpleReport = facade.unmarshall(file);

	try (FileOutputStream fos = new FileOutputStream("target/report.pdf")) {
		Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, fos);
		Result result = new SAXResult(fop.getDefaultHandler());
		facade.generatePdfReport(simpleReport, result);
	}
	
	File pdfReport = new File("target/report.pdf");
	assertTrue(pdfReport.exists());
	assertTrue(pdfReport.delete(), "Cannot delete PDF document (IO error)");
	assertFalse(pdfReport.exists());
}
 
Example #9
Source File: ApacheFopWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/** Transform an xsl-fo file to the specified file format.
 * @param srcFile The xsl-fo File instance
 * @param destFile The target (result) File instance
 * @param stylesheetFile Optional stylesheet File instance
 * @param outputFormat Optional output format, defaults to "application/pdf"
 */
public static void transform(File srcFile, File destFile, File stylesheetFile, String outputFormat) throws IOException, FOPException {
    StreamSource src = new StreamSource(srcFile);
    StreamSource stylesheet = stylesheetFile == null ? null : new StreamSource(stylesheetFile);
    BufferedOutputStream dest = new BufferedOutputStream(new FileOutputStream(destFile));
    Fop fop = createFopInstance(dest, outputFormat);
    transform(src, stylesheet, fop);
    dest.close();
}
 
Example #10
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 #11
Source File: FopSerializer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public void setOutputStream(final OutputStream outputStream) {
    try {
        Fop fop = FOP_FACTORY.newFop(this.outputFormat, outputStream);
        ContentHandler fopContentHandler = fop.getDefaultHandler();

        this.setContentHandler(fopContentHandler);
    } catch (FOPException e) {
        throw new ProcessingException("Impossible to initialize FOPSerializer", e);
    }
}
 
Example #12
Source File: ApacheFopWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/** Transform an xsl-fo InputStream to the specified OutputStream format.
 * @param srcStream The xsl-fo InputStream instance
 * @param destStream The target (result) OutputStream instance
 * @param stylesheetStream Optional stylesheet InputStream instance
 * @param outputFormat Optional output format, defaults to "application/pdf"
 */
public static void transform(InputStream srcStream, OutputStream destStream, InputStream stylesheetStream, String outputFormat) throws FOPException {
    StreamSource src = new StreamSource(srcStream);
    StreamSource stylesheet = stylesheetStream == null ? null : new StreamSource(stylesheetStream);
    Fop fop = createFopInstance(destStream, outputFormat);
    transform(src, stylesheet, fop);
}
 
Example #13
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 #14
Source File: FopTask.java    From pcgen with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Run the FO to PDF/AWT conversion. This automatically closes any provided OutputStream for
 * this FopTask.
 */
@Override
public void run()
{
	try (OutputStream out = outputStream)
	{
		userAgent.setProducer("PC Gen Character Generator");
		userAgent.setAuthor(System.getProperty("user.name"));
		userAgent.setCreationDate(Date.from(LocalDateTime.now().toInstant(ZoneOffset.ofHours(0))));

		userAgent.getEventBroadcaster().addEventListener(new FOPEventListener());

		String mimeType;
		if (renderer != null)
		{
			userAgent.setKeywords("PCGEN FOP PREVIEW");
			mimeType = MimeConstants.MIME_FOP_AWT_PREVIEW;
		}
		else
		{
			userAgent.setKeywords("PCGEN FOP PDF");
			mimeType = org.apache.xmlgraphics.util.MimeConstants.MIME_PDF;
		}
		Fop fop;
		if (out != null)
		{
			fop = FOP_FACTORY.newFop(mimeType, userAgent, out);
		}
		else
		{
			fop = FOP_FACTORY.newFop(mimeType, userAgent);
		}

		Transformer transformer;
		if (xsltSource != null)
		{
			transformer = TRANS_FACTORY.newTransformer(xsltSource);
		}
		else
		{
			transformer = TRANS_FACTORY.newTransformer(); // identity transformer		
		}
		transformer.setErrorListener(new FOPErrorListener());
		transformer.transform(inputSource, new SAXResult(fop.getDefaultHandler()));
	}
	catch (TransformerException | FOPException | IOException e)
	{
		errorBuilder.append(e.getMessage()).append(Constants.LINE_SEPARATOR);
		Logging.errorPrint("Exception in FopTask:run", e);
	}
	catch (RuntimeException ex)
	{
		errorBuilder.append(ex.getMessage()).append(Constants.LINE_SEPARATOR);
		Logging.errorPrint("Unexpected exception in FopTask:run: ", ex);
	}
}
 
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: FopTask.java    From pcgen with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Run the FO to PDF/AWT conversion. This automatically closes any provided OutputStream for
 * this FopTask.
 */
@Override
public void run()
{
	try (OutputStream out = outputStream)
	{
		userAgent.setProducer("PC Gen Character Generator");
		userAgent.setAuthor(System.getProperty("user.name"));
		userAgent.setCreationDate(Date.from(LocalDateTime.now().toInstant(ZoneOffset.ofHours(0))));

		userAgent.getEventBroadcaster().addEventListener(new FOPEventListener());

		String mimeType;
		if (renderer != null)
		{
			userAgent.setKeywords("PCGEN FOP PREVIEW");
			mimeType = MimeConstants.MIME_FOP_AWT_PREVIEW;
		}
		else
		{
			userAgent.setKeywords("PCGEN FOP PDF");
			mimeType = org.apache.xmlgraphics.util.MimeConstants.MIME_PDF;
		}
		Fop fop;
		if (out != null)
		{
			fop = FOP_FACTORY.newFop(mimeType, userAgent, out);
		}
		else
		{
			fop = FOP_FACTORY.newFop(mimeType, userAgent);
		}

		Transformer transformer;
		if (xsltSource != null)
		{
			transformer = TRANS_FACTORY.newTransformer(xsltSource);
		}
		else
		{
			transformer = TRANS_FACTORY.newTransformer(); // identity transformer		
		}
		transformer.setErrorListener(new FOPErrorListener());
		transformer.transform(inputSource, new SAXResult(fop.getDefaultHandler()));
	}
	catch (TransformerException | FOPException | IOException e)
	{
		errorBuilder.append(e.getMessage()).append(Constants.LINE_SEPARATOR);
		Logging.errorPrint("Exception in FopTask:run", e);
	}
	catch (RuntimeException ex)
	{
		errorBuilder.append(ex.getMessage()).append(Constants.LINE_SEPARATOR);
		Logging.errorPrint("Unexpected exception in FopTask:run: ", ex);
	}
}
 
Example #17
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 #18
Source File: OutputServices.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static Map<String, Object> createFileFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
    Locale locale = (Locale) serviceContext.get("locale");
    Delegator delegator = dctx.getDelegator();
    String screenLocation = (String) serviceContext.remove("screenLocation");
    Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
    String contentType = (String) serviceContext.remove("contentType");
    String filePath = (String) serviceContext.remove("filePath");
    String fileName = (String) serviceContext.remove("fileName");

    if (UtilValidate.isEmpty(screenContext)) {
        screenContext = new HashMap<>();
    }
    screenContext.put("locale", locale);
    if (UtilValidate.isEmpty(contentType)) {
        contentType = "application/pdf";
    }

    try {
        MapStack<String> screenContextTmp = RenderMapStack.createRenderContext(); // SCIPIO: Dedicated context class: MapStack.create();
        screenContextTmp.put("locale", locale);

        Writer writer = new StringWriter();
        // substitute the freemarker variables...
        ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(EntityUtilProperties.getPropertyValue("widget", "screenfop.name", dctx.getDelegator()),
                EntityUtilProperties.getPropertyValue("widget", "screenfop.screenrenderer", dctx.getDelegator()));

        // SCIPIO: TODO: form widget renderer support
        //FormStringRenderer foFormRenderer = new MacroFormRenderer(EntityUtilProperties.getPropertyValue("widget", "screenfop.name", dctx.getDelegator()),
        //        EntityUtilProperties.getPropertyValue("widget", "screenfop.formrenderer", dctx.getDelegator()), request, response);

        ScreenRenderer screensAtt = ScreenRenderer.makeWithEnvAwareFetching(writer, screenContextTmp, foScreenStringRenderer);
        screensAtt.populateContextForService(dctx, screenContext);
        screenContextTmp.putAll(screenContext);
        // SCIPIO: TODO: form widget renderer support
        //screensAtt.getContext().put("formStringRenderer", foFormRenderer);
        WidgetRenderOptions.setInContext(screensAtt.getContext(), WidgetRenderOptions.create(dctx, locale).setWarnMissingFormRenderer(true)); // SCIPIO: for logging; see ModelScreenWidget
        screensAtt.render(screenLocation);

        // create the input stream for the generation
        StreamSource src = new StreamSource(new StringReader(writer.toString()));

        // create the output stream for the generation
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
        ApacheFopWorker.transform(src, null, fop);

        baos.flush();
        baos.close();

        fileName += UtilDateTime.nowAsString();
        if ("application/pdf".equals(contentType)) {
            fileName += ".pdf";
        } else if ("application/postscript".equals(contentType)) {
            fileName += ".ps";
        } else if ("text/plain".equals(contentType)) {
            fileName += ".txt";
        }
        if (UtilValidate.isEmpty(filePath)) {
            filePath = EntityUtilProperties.getPropertyValue("content", "content.output.path", "/output", delegator);
        }
        File file = new File(filePath, fileName);

        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baos.toByteArray());
        fos.close();

    } catch (Exception e) { // SCIPIO: 2018-10-09: Kept Exception for now
        Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
    }

    return ServiceUtil.returnSuccess();
}
 
Example #19
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 #20
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);
            }
        });
    });

}
 
Example #21
Source File: ApacheFopWorker.java    From scipio-erp with Apache License 2.0 2 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"
 * @return Fop instance
 */
public static Fop createFopInstance(OutputStream out, String outputFormat) throws FOPException {
    return createFopInstance(out, outputFormat, null);
}