/**
   * 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;
    }
  }
Ejemplo n.º 2
0
  /** {@inheritDoc} */
  @Override
  public void init() throws ServletException {
    this.uriResolver = new RepositoryURIResolver();
    this.transFactory = TransformerFactory.newInstance();
    this.transFactory.setURIResolver(this.uriResolver);

    // Configure FopFactory as desired
    this.fopFactory = FopFactory.newInstance();
    this.fopFactory.setURIResolver(this.uriResolver);
    configureFopFactory();
  }
Ejemplo n.º 3
0
  /**
   * 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;
  }
Ejemplo n.º 4
0
  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;
    }
  }
Ejemplo n.º 5
0
/**
 * Debug tool to create and process large FO files by replicating them a specified number of times.
 */
public class MemoryEater {

  private SAXTransformerFactory tFactory =
      (SAXTransformerFactory) SAXTransformerFactory.newInstance();
  private FopFactory fopFactory = FopFactory.newInstance();
  private Templates replicatorTemplates;

  private Stats stats;

  public MemoryEater() throws TransformerConfigurationException, MalformedURLException {
    File xsltFile = new File("test/xsl/fo-replicator.xsl");
    Source xslt = new StreamSource(xsltFile);
    replicatorTemplates = tFactory.newTemplates(xslt);
  }

  private void eatMemory(File foFile, int runRepeats, int replicatorRepeats) throws Exception {
    stats = new Stats();
    for (int i = 0; i < runRepeats; i++) {
      eatMemory(i, foFile, replicatorRepeats);
      stats.progress(i, runRepeats);
    }
    stats.dumpFinalStats();
    System.out.println(stats.getGoogleChartURL());
  }

  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);
    }
  }

  private static void prompt() throws IOException {
    BufferedReader in = new BufferedReader(new java.io.InputStreamReader(System.in));
    System.out.print("Press return to continue...");
    in.readLine();
  }

  /**
   * Main method.
   *
   * @param args the command-line arguments
   */
  public static void main(String[] args) {
    boolean doPrompt = true; // true if you want a chance to start the monitoring console
    try {
      int replicatorRepeats = 2;
      int runRepeats = 1;
      if (args.length > 0) {
        replicatorRepeats = Integer.parseInt(args[0]);
      }
      if (args.length > 1) {
        runRepeats = Integer.parseInt(args[1]);
      }
      File testFile = new File("examples/fo/basic/readme.fo");

      System.out.println(
          "MemoryEater! About to replicate the test file "
              + replicatorRepeats
              + " times and run it "
              + runRepeats
              + " times...");
      if (doPrompt) {
        prompt();
      }

      System.out.println("Processing...");
      long start = System.currentTimeMillis();

      MemoryEater app = new MemoryEater();
      app.eatMemory(testFile, runRepeats, replicatorRepeats);

      long duration = System.currentTimeMillis() - start;
      System.out.println("Success! Job took " + duration + " ms");

      if (doPrompt) {
        prompt();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Ejemplo n.º 6
0
/** This class demonstrates the use of the AWT Viewer. */
public class ExampleAWTViewer {

  // configure fopFactory as desired
  private FopFactory fopFactory = FopFactory.newInstance();

  /**
   * 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);
    }
  }

  /**
   * Main method.
   *
   * @param args the command-line arguments
   */
  public static void main(String[] args) {
    try {
      System.out.println("FOP ExampleAWTViewer\n");
      System.out.println("Preparing...");

      // Setup directories
      File baseDir = new File(".");
      File outDir = new File(baseDir, "out");
      outDir.mkdirs();

      // Setup input and output files
      File fofile = new File(baseDir, "xml/fo/helloworld.fo");

      System.out.println("Input: XSL-FO (" + fofile + ")");
      System.out.println("Output: AWT Viewer");
      System.out.println();
      System.out.println("Starting AWT Viewer...");

      ExampleAWTViewer app = new ExampleAWTViewer();
      app.viewFO(fofile);

      System.out.println("Success!");
    } catch (Exception e) {
      System.err.println(ExceptionUtil.printStackTrace(e));
      System.exit(-1);
    }
  }
}
Ejemplo n.º 7
0
  @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;
  }
Ejemplo n.º 8
0
  /*
   * 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);
    }
  }