private void eatMemory(int callIndex, File foFile, int replicatorRepeats) throws Exception { Source src = new StreamSource(foFile); Transformer transformer = replicatorTemplates.newTransformer(); transformer.setParameter("repeats", new Integer(replicatorRepeats)); OutputStream out = new NullOutputStream(); // write to /dev/nul try { FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.setBaseURL(foFile.getParentFile().toURL().toExternalForm()); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); stats.notifyPagesProduced(fop.getResults().getPageCount()); if (callIndex == 0) { System.out.println( foFile.getName() + " generates " + fop.getResults().getPageCount() + " pages."); } stats.checkStats(); } finally { IOUtils.closeQuietly(out); } }
protected void render( FopFactory fopFactory, String outputFormat, Source foDocumentSrc, PlaceholderReplacementHandler.PlaceholderLookup placeholderLookup, OutputStream outputStream) throws Docx4JException { Fop fop = null; Result result = null; try { fop = fopFactory.newFop(outputFormat, 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); }
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); }
/** * Takes a DOM structure and renders a PDF * * @param doc DOM structure * @param xslFileName XSL file to use to translate the DOM document to FOP */ @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"; if (getClass().getClassLoader().getResourceAsStream(xslFileName) == null) { xslFileName = "participants-all-attrs_" + currentLocale.getCountry() + ".xsl"; if (getClass().getClassLoader().getResourceAsStream(xslFileName) == null) { // We use the default file xslFileName = "participants-all-attrs.xsl"; } } } String configFileName = "userconfig.xml"; DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); try { Configuration cfg = cfgBuilder.build(getClass().getClassLoader().getResourceAsStream(configFileName)); 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("titleSection", rb.getString("sitegen.siteinfolist.title.section")); transformer.setParameter("titleId", rb.getString("sitegen.siteinfolist.title.id")); 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) { e.printStackTrace(); log.warn(this + ".generatePDF(): " + e); return; } }
/** * Transform an xml tree to PDF using XSL-FOP * putting the result to a stream (uses a * stylesheet on disk) */ public static String transformFOP(String uploadDir, Element xml, String styleSheetPath) throws Exception { String file = uploadDir + UUID.randomUUID().toString() + ".pdf"; // Step 1: Construct a FopFactory // (reuse if you plan to render multiple documents!) FopFactory fopFactory = FopFactory.newInstance(); // Step 2: Set up output stream. // Note: Using BufferedOutputStream for performance reasons (helpful // with FileOutputStreams). OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file))); try { // 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 = TransformerFactoryFactory.getTransformerFactory(); factory.setURIResolver(new JeevesURIResolver()); Source xslt = new StreamSource(new File(styleSheetPath)); try { factory.setAttribute(FeatureKeys.VERSION_WARNING, false); factory.setAttribute(FeatureKeys.LINE_NUMBERING, true); factory.setAttribute(FeatureKeys.RECOVERY_POLICY, Configuration.RECOVER_SILENTLY); } catch (IllegalArgumentException e) { Log.warning(Log.ENGINE, "WARNING: transformerfactory doesnt like saxon attributes!"); // e.printStackTrace(); } finally { Transformer transformer = factory.newTransformer(xslt); // Step 5: Setup input and output for XSLT transformation // Setup input stream Source src = new JDOMSource(new Document((Element) xml.detach())); // 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); } } finally { // Clean-up out.close(); } return file; }
/** * Renders an input file (XML or XSL-FO) into a PDF file. It uses the JAXP transformer given to * optionally transform the input document to XSL-FO. The transformer may be an identity * transformer in which case the input must already be XSL-FO. The PDF is written to a byte array * that is returned as the method's result. * * @param src Input XML or XSL-FO * @param transformer Transformer to use for optional transformation * @param response HTTP response object * @throws FOPException If an error occurs during the rendering of the XSL-FO * @throws TransformerException If an error occurs during XSL transformation * @throws IOException In case of an I/O problem */ protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); // Setup output ByteArrayOutputStream out = new ByteArrayOutputStream(); // Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); // Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); // Start the transformation and rendering process transformer.transform(src, res); // Return the result sendPDF(out.toByteArray(), response); }
/** * Display an FO file in the AWT Preview. * * @param fo the FO file * @throws IOException In case of an I/O problem * @throws FOPException In case of a problem during layout * @throws TransformerException In case of a problem during XML processing */ public void viewFO(File fo) throws IOException, FOPException, TransformerException { // Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_FOP_AWT_PREVIEW); try { // Load XSL-FO file (you can also do an XSL transformation here) TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); Source src = new StreamSource(fo); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); } catch (Exception e) { if (e instanceof FOPException) { throw (FOPException) e; } throw new FOPException(e); } }
/** * For first pass of two pass process, invoke org.apache.fop.apps.FormattingResults which can tell * us the number of pages in each page sequence, and in the document as a whole. * * @param fopFactory * @param outputFormat * @param foDocumentSrc * @param placeholderLookup * @return * @throws Docx4JException */ protected FormattingResults calcResults( FopFactory fopFactory, String outputFormat, Source foDocumentSrc, PlaceholderReplacementHandler.PlaceholderLookup placeholderLookup) throws Docx4JException { Fop fop = null; Result result = null; try { fop = fopFactory.newFop(outputFormat, new NullOutputStream()); result = 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); return fop.getResults(); }
public void generateGeneric() { String tMIME = null; if (genMode.equals("PDF")) { tMIME = MimeConstants.MIME_PDF; } else { tMIME = MimeConstants.MIME_RTF; } try { System.out.println("FOP Transformation\n"); System.out.println("Preparing..."); String fileName = new File(xsltfile).getName(); // File xsltfile = new File("lib/xsl2/xslt/base/fo/" + fileName); File xsltfile = new File("lib/xsl/fo/" + fileName); // configure fopFactory.4. as desired // FopFactoryConfig ffc = new FopFactoryConfig(); // FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()) ; // .newInstance(); FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); foUserAgent.setTitle("TEST"); // configure foUserAgent as desired // Setup output OutputStream out = new java.io.FileOutputStream(outputfile); out = new java.io.BufferedOutputStream(out); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xsltfile)); // test run to get total pagecount Fop fop = fopFactory.newFop(tMIME, foUserAgent, out); Source src = new StreamSource(xmlfile); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); // Get total page count String pageCount = "UNAVAILABLE"; if (fop.getResults() != null) { pageCount = Integer.toString(fop.getResults().getPageCount()); } else { } System.out.println("totalcc " + pageCount); // real run // Construct fop with desired output format fop = fopFactory.newFop(tMIME, foUserAgent, out); // set draft parameter String draftImageFn = new File("lib/xsl/images/draft.png").toURI().toString(); // .getAbsolutePath(); transformer.setParameter("draft.watermark.image", draftImageFn); System.out.println(transformer.getParameter("draft.watermark.image")); if (isDraftMode) { transformer.setParameter("draft.mode", "yes"); } else { transformer.setParameter("draft.mode", "no"); } transformer.setParameter("draft.mode", pageCount); // set pagecount parameter transformer.setParameter("ebnf.statement.terminator", pageCount); // Resulting SAX events (the generated FO) must be piped // through // to FOP res = new SAXResult(fop.getDefaultHandler()); // Start XSLT transformation and FOP processing transformer.transform(src, res); } finally { out.close(); status = 0; } System.out.println("Success!"); System.out.println("DocBook " + genMode + " generation COMPLETED"); } catch (Exception e) { e.printStackTrace(System.err); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); status = 2; return; } }
@Override protected boolean executeAction() { String printFileName = null; IActionSequenceResource printFileResource = null; PrinterAction printAction = (PrinterAction) getActionDefinition(); if (printAction.getPrintfile() != ActionInputConstant.NULL_INPUT) { printFileName = printAction.getPrintfile().getStringValue(); } else if (printAction.getResourcesPrintFile() != null) { org.pentaho.actionsequence.dom.IActionResource tempResource = printAction.getResourcesPrintFile(); printFileResource = getResource(tempResource.getName()); } InputStream inStream = null; String printerName = printAction.getPrinterName().getStringValue(PrintComponent.DEFAULT_PRINTER); String lastPrinter = printAction.getDefaultPrinter().getStringValue(); if ((printAction.getOutputPrinterName() != null) && !printerName.equals("")) { // $NON-NLS-1$ IActionOutput output = printAction.getOutputPrinterName(); output.setValue(printerName); if (printAction.getOutputDefaultPrinter() != null) { IActionOutput defaultPrinterOutput = printAction.getOutputDefaultPrinter(); defaultPrinterOutput.setValue(printerName); } return true; } PrintService printer = getPrinterInternal(printerName, lastPrinter); if (printer == null) { if (!feedbackAllowed()) { error( Messages.getInstance() .getErrorString("PrintComponent.ERROR_0002_NO_SUITABLE_PRINTER")); // $NON-NLS-1$ return false; } // we created the printer feedback entry already return true; } if (printAction.getOutputDefaultPrinter() != null) { IActionOutput defaultPrinterOutput = printAction.getOutputDefaultPrinter(); defaultPrinterOutput.setValue(printerName); } // Get the number of copies int copies = printAction.getCopies().getIntValue(1); // Check for a valid printFileName or printFile Resource if (printFileName != null) { inStream = ActionSequenceResource.getInputStream(printFileName, LocaleHelper.getLocale()); } else if (printFileResource != null) { try { inStream = getResourceInputStream(printFileResource); } catch (FileNotFoundException e) { return false; } } else if (printAction.getReportOutput() != ActionInputConstant.NULL_INPUT) { inStream = getInputStream(PrinterAction.REPORT_OUTPUT); } else { // This should never happen if we validated ok. return false; } try { // Set the input source for sending to the driver. // InputSource source = new InputSource(inStream); try { FopFactory fopFactory = FopFactory.newInstance(); FOUserAgent userAgent = fopFactory.newFOUserAgent(); PrinterJob printerJob = PrinterJob.getPrinterJob(); // Set up our own PrintRenderer instance so we can supply a special PrinterJob instance. PrintRenderer renderer = new PrintRenderer(printerJob, copies); renderer.setUserAgent(userAgent); userAgent.setRendererOverride(renderer); // Construct fop with desired output format (here, it is set through the user agent) Fop fop = fopFactory.newFop(userAgent); // Setup JAXP using identity transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // identity transformer // Setup input stream Source src = new StreamSource(inStream); // 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); } catch (Exception ex) { return false; } } finally { try { inStream.close(); } catch (IOException ex) { // TODO: Provide message here... ex.printStackTrace(); } } return true; }
/* * Actual implementation of the rendering process. When a function in this * module is called, this method is executed with the given inputs. @param * Sequence[] args (XSL-FO, mime-type, parameters) @param Sequence * contextSequence (default sequence) * * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], * org.exist.xquery.value.Sequence) */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { // gather input XSL-FO document // if no input document (empty), return empty result as we need data to // process if (args[0].isEmpty()) return Sequence.EMPTY_SEQUENCE; Item inputNode = args[0].itemAt(0); // get mime-type String mimeType = args[1].getStringValue(); // get parameters Properties parameters = new Properties(); if (!args[2].isEmpty()) { parameters = ModuleUtils.parseParameters(((NodeValue) args[2].itemAt(0)).getNode()); } try { // setup a transformer handler TransformerHandler handler = TransformerFactoryAllocator.getTransformerFactory(context.getBroker()) .newTransformerHandler(); Transformer transformer = handler.getTransformer(); // set the parameters if any if (parameters.size() > 0) { Enumeration keys = parameters.keys(); while (keys.hasMoreElements()) { String name = (String) keys.nextElement(); String value = parameters.getProperty(name); transformer.setParameter(name, value); } } // setup the FopFactory FopFactory fopFactory = FopFactory.newInstance(); if (args.length == 4 && args[3] != null && !args[3].isEmpty()) { FopConfigurationBuilder cfgBuilder = new FopConfigurationBuilder(context.getBroker()); Configuration cfg = cfgBuilder.buildFromItem(args[3].itemAt(0)); fopFactory.setUserConfig(cfg); } // setup the foUserAgent, using given parameters held in the // transformer handler FOUserAgent foUserAgent = setupFOUserAgent(fopFactory.newFOUserAgent(), parameters, transformer); // create new instance of FOP using the mimetype, the created user // agent, and the output stream ByteArrayOutputStream baos = new ByteArrayOutputStream(); Fop fop = fopFactory.newFop(mimeType, foUserAgent, baos); // Obtain FOP's DefaultHandler DefaultHandler dh = fop.getDefaultHandler(); // process the XSL-FO dh.startDocument(); inputNode.toSAX(context.getBroker(), dh, new Properties()); dh.endDocument(); // return the result return new Base64Binary(baos.toByteArray()); } catch (TransformerException te) { throw new XPathException(te); } catch (SAXException se) { throw new XPathException(se); } }