예제 #1
0
  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);
    }
  }
예제 #2
0
  /**
   * Setup the UserAgent for FOP, from given parameters *
   *
   * @param transformer Created based on the XSLT, so containing any parameters to the XSL-FO
   *     specified in the XQuery
   * @param parameters any user defined parameters to the XSL-FO process
   * @return FOUserAgent The generated FOUserAgent to include any parameters passed in
   */
  private FOUserAgent setupFOUserAgent(
      FOUserAgent foUserAgent, Properties parameters, Transformer transformer)
      throws TransformerException {

    // setup the foUserAgent as per the parameters given
    foUserAgent.setProducer("eXist with Apache FOP");

    if (transformer.getParameter("FOPauthor") != null)
      foUserAgent.setAuthor(parameters.getProperty("author"));

    if (transformer.getParameter("FOPtitle") != null)
      foUserAgent.setTitle(parameters.getProperty("title"));

    if (transformer.getParameter("FOPkeywords") != null)
      foUserAgent.setTitle(parameters.getProperty("keywords"));

    if (transformer.getParameter("FOPdpi") != null) {
      String dpiStr = (String) transformer.getParameter("dpi");
      try {
        foUserAgent.setTargetResolution(Integer.parseInt(dpiStr));
      } catch (NumberFormatException nfe) {
        throw new TransformerException(
            "Cannot parse value of \"dpi\" - " + dpiStr + " to configure FOUserAgent");
      }
    }

    return foUserAgent;
  }
예제 #3
0
  /**
   * @see Results
   * @param targetResolution The Target Output Resolution.
   * @param ff The FopFactory used to create the FOUserAgent used to convert.
   * @param xmlSource XML file to be used in conversion.
   * @param xsltSource XSLT file to be used in translation.
   * @return A Result Class containing the conversion results
   */
  public static Results translate(
      int targetResolution, FopFactory ff, Source xmlSource, Source xsltSource) {

    FOUserAgent fua = getFopUserAgent(ff);
    fua.setTargetResolution(targetResolution);

    return translate(fua, xmlSource, xsltSource);
  }
  /**
   * Tests resource optimization with the {@link PSDocumentHandler}.
   *
   * @throws Exception if an error occurs
   */
  public void testResourceOptimizationWithIF() throws Exception {
    FOUserAgent ua = fopFactory.newFOUserAgent();
    PSDocumentHandler handler = new PSDocumentHandler();
    handler.setContext(new IFContext(ua));
    // This is the important part: we're enabling resource optimization
    handler.getPSUtil().setOptimizeResources(true);
    ua.setDocumentHandlerOverride(handler);

    // Prepare output file
    File outputFile =
        renderFile(ua, "ps-resources.fo", "-if-l" + handler.getPSUtil().getLanguageLevel());
    verifyPostScriptFile(outputFile);
  }
  /**
   * Tests resource optimization with the {@link PSRenderer}.
   *
   * @throws Exception if an error occurs
   */
  public void testResourceOptimizationWithRenderer() throws Exception {
    FOUserAgent ua = fopFactory.newFOUserAgent();
    PSRenderer renderer = new PSRenderer();
    renderer.setUserAgent(ua);
    // This is the important part: we're enabling resource optimization
    renderer.getPSUtil().setOptimizeResources(true);
    ua.setRendererOverride(renderer);

    // Prepare output file
    File outputFile =
        renderFile(ua, "ps-resources.fo", "-rend-l" + renderer.getPSUtil().getLanguageLevel());
    verifyPostScriptFile(outputFile);
  }
예제 #6
0
 @Override
 public void doFOPPublish(FOUserAgent foUserAgent) {
   AWTRenderer renderer = new AWTRenderer();
   renderer.setPreviewDialogDisplayed(true);
   foUserAgent.setRendererOverride(renderer);
   renderer.setUserAgent(foUserAgent);
 }
예제 #7
0
  /**
   * <code>FOTreeBuilder</code> constructor
   *
   * @param outputFormat the MIME type of the output format to use (ex. "application/pdf").
   * @param foUserAgent the {@link FOUserAgent} in effect for this process
   * @param stream the <code>OutputStream</code> to direct the results to
   * @throws FOPException if the <code>FOTreeBuilder</code> cannot be properly created
   */
  public FOTreeBuilder(String outputFormat, FOUserAgent foUserAgent, OutputStream stream)
      throws FOPException {

    this.userAgent = foUserAgent;
    this.elementMappingRegistry = userAgent.getFactory().getElementMappingRegistry();
    // This creates either an AreaTreeHandler and ultimately a Renderer, or
    // one of the RTF-, MIF- etc. Handlers.
    foEventHandler =
        foUserAgent.getRendererFactory().createFOEventHandler(foUserAgent, outputFormat, stream);
    builderContext = new FOTreeBuilderContext();
    builderContext.setPropertyListMaker(
        new PropertyListMaker() {
          public PropertyList make(FObj fobj, PropertyList parentPropertyList) {
            return new StaticPropertyList(fobj, parentPropertyList);
          }
        });
  }
예제 #8
0
 /** {@inheritDoc} */
 public void endDocument() throws SAXException {
   this.delegate.endDocument();
   if (this.rootFObj == null && empty) {
     FOValidationEventProducer eventProducer =
         FOValidationEventProducer.Provider.get(userAgent.getEventBroadcaster());
     eventProducer.emptyDocument(this);
   }
   rootFObj = null;
   if (log.isDebugEnabled()) {
     log.debug("Parsing of document complete");
   }
   foEventHandler.endDocument();
 }
  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;
    }
  }
 /**
  * Main constructor
  *
  * @param foUserAgent the apps.FOUserAgent instance for this process
  */
 public FOEventHandler(FOUserAgent foUserAgent) {
   this.foUserAgent = foUserAgent;
   this.fontInfo = new FontInfo();
   this.fontInfo.setEventListener(new FontEventAdapter(foUserAgent.getEventBroadcaster()));
 }
예제 #11
0
  /**
   * Parse a color specified using the fop-rgb-named-color() function.
   *
   * @param value the function call
   * @return a color if possible
   * @throws PropertyException if the format is wrong.
   */
  private static Color parseAsFopRgbNamedColor(FOUserAgent foUserAgent, String value)
      throws PropertyException {
    Color parsedColor;
    int poss = value.indexOf("(");
    int pose = value.indexOf(")");
    if (poss != -1 && pose != -1) {
      String[] args = value.substring(poss + 1, pose).split(",");

      try {
        if (args.length != 6) {
          throw new PropertyException("rgb-named-color() function must have 6 arguments");
        }

        // Set up fallback sRGB value
        Color sRGB = parseFallback(args, value);

        /* Get and verify ICC profile name */
        String iccProfileName = args[3].trim();
        if (iccProfileName == null || "".equals(iccProfileName)) {
          throw new PropertyException("ICC profile name missing");
        }
        ICC_ColorSpace colorSpace = null;
        String iccProfileSrc;
        if (isPseudoProfile(iccProfileName)) {
          throw new IllegalArgumentException(
              "Pseudo-profiles are not allowed with fop-rgb-named-color()");
        } else {
          /* Get and verify ICC profile source */
          iccProfileSrc = args[4].trim();
          if (iccProfileSrc == null || "".equals(iccProfileSrc)) {
            throw new PropertyException("ICC profile source missing");
          }
          iccProfileSrc = unescapeString(iccProfileSrc);
        }

        // color name
        String colorName = unescapeString(args[5].trim());

        /* Ask FOP factory to get ColorSpace for the specified ICC profile source */
        if (foUserAgent != null && iccProfileSrc != null) {
          RenderingIntent renderingIntent = RenderingIntent.AUTO;
          // TODO connect to fo:color-profile/@rendering-intent
          colorSpace =
              (ICC_ColorSpace)
                  foUserAgent
                      .getColorSpaceCache()
                      .get(iccProfileName, iccProfileSrc, renderingIntent);
        }
        if (colorSpace != null) {
          ICC_Profile profile = colorSpace.getProfile();
          if (NamedColorProfileParser.isNamedColorProfile(profile)) {
            NamedColorProfileParser parser = new NamedColorProfileParser();
            NamedColorProfile ncp = parser.parseProfile(profile, iccProfileName, iccProfileSrc);
            NamedColorSpace ncs = ncp.getNamedColor(colorName);
            if (ncs != null) {
              parsedColor = new ColorWithFallback(ncs, new float[] {1.0f}, 1.0f, null, sRGB);
            } else {
              log.warn(
                  "Color '"
                      + colorName
                      + "' does not exist in named color profile: "
                      + iccProfileSrc);
              parsedColor = sRGB;
            }
          } else {
            log.warn("ICC profile is no named color profile: " + iccProfileSrc);
            parsedColor = sRGB;
          }
        } else {
          // ICC profile could not be loaded - use rgb replacement values */
          log.warn(
              "Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values.");
          parsedColor = sRGB;
        }
      } catch (IOException ioe) {
        // wrap in a PropertyException
        throw new PropertyException(ioe);
      } catch (RuntimeException re) {
        throw new PropertyException(re);
        // wrap in a PropertyException
      }
    } else {
      throw new PropertyException(
          "Unknown color format: "
              + value
              + ". Must be fop-rgb-named-color(r,g,b,NCNAME,src,color-name)");
    }
    return parsedColor;
  }
예제 #12
0
  /**
   * Parse a color specified using the fop-rgb-icc() function.
   *
   * @param value the function call
   * @return a color if possible
   * @throws PropertyException if the format is wrong.
   */
  private static Color parseAsFopRgbIcc(FOUserAgent foUserAgent, String value)
      throws PropertyException {
    Color parsedColor;
    int poss = value.indexOf("(");
    int pose = value.indexOf(")");
    if (poss != -1 && pose != -1) {
      String[] args = value.substring(poss + 1, pose).split(",");

      try {
        if (args.length < 5) {
          throw new PropertyException("Too few arguments for rgb-icc() function");
        }

        // Set up fallback sRGB value
        Color sRGB = parseFallback(args, value);

        /* Get and verify ICC profile name */
        String iccProfileName = args[3].trim();
        if (iccProfileName == null || "".equals(iccProfileName)) {
          throw new PropertyException("ICC profile name missing");
        }
        ColorSpace colorSpace = null;
        String iccProfileSrc = null;
        if (isPseudoProfile(iccProfileName)) {
          if (CMYK_PSEUDO_PROFILE.equalsIgnoreCase(iccProfileName)) {
            colorSpace = ColorSpaces.getDeviceCMYKColorSpace();
          } else if (SEPARATION_PSEUDO_PROFILE.equalsIgnoreCase(iccProfileName)) {
            colorSpace = new NamedColorSpace(args[5], sRGB, SEPARATION_PSEUDO_PROFILE, null);
          } else {
            assert false : "Incomplete implementation";
          }
        } else {
          /* Get and verify ICC profile source */
          iccProfileSrc = args[4].trim();
          if (iccProfileSrc == null || "".equals(iccProfileSrc)) {
            throw new PropertyException("ICC profile source missing");
          }
          iccProfileSrc = unescapeString(iccProfileSrc);
        }
        /* ICC profile arguments */
        int componentStart = 4;
        if (colorSpace instanceof NamedColorSpace) {
          componentStart++;
        }
        float[] iccComponents = new float[args.length - componentStart - 1];
        for (int ix = componentStart; ++ix < args.length; ) {
          iccComponents[ix - componentStart - 1] = Float.parseFloat(args[ix].trim());
        }
        if (colorSpace instanceof NamedColorSpace && iccComponents.length == 0) {
          iccComponents = new float[] {1.0f}; // full tint if not specified
        }

        /* Ask FOP factory to get ColorSpace for the specified ICC profile source */
        if (foUserAgent != null && iccProfileSrc != null) {
          RenderingIntent renderingIntent = RenderingIntent.AUTO;
          // TODO connect to fo:color-profile/@rendering-intent
          colorSpace =
              foUserAgent.getColorSpaceCache().get(iccProfileName, iccProfileSrc, renderingIntent);
        }
        if (colorSpace != null) {
          // ColorSpace is available
          if (ColorSpaces.isDeviceColorSpace(colorSpace)) {
            // Device-specific colors are handled differently:
            // sRGB is the primary color with the CMYK as the alternative
            Color deviceColor = new Color(colorSpace, iccComponents, 1.0f);
            float[] rgbComps = sRGB.getRGBColorComponents(null);
            parsedColor =
                new ColorWithAlternatives(
                    rgbComps[0], rgbComps[1], rgbComps[2], new Color[] {deviceColor});
          } else {
            parsedColor = new ColorWithFallback(colorSpace, iccComponents, 1.0f, null, sRGB);
          }
        } else {
          // ICC profile could not be loaded - use rgb replacement values */
          log.warn(
              "Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values.");
          parsedColor = sRGB;
        }
      } catch (RuntimeException re) {
        throw new PropertyException(re);
      }
    } else {
      throw new PropertyException(
          "Unknown color format: " + value + ". Must be fop-rgb-icc(r,g,b,NCNAME,src,....)");
    }
    return parsedColor;
  }
예제 #13
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;
  }
예제 #14
0
 /** @return a {@link Locator} instance if it is available and not disabled */
 protected Locator getEffectiveLocator() {
   return (userAgent.isLocatorEnabled() ? this.locator : null);
 }
  /** {@inheritDoc} */
  public void activateLayout() {
    initialize();

    FOUserAgent userAgent = pageSeq.getUserAgent();
    ImageManager imageManager = userAgent.getFactory().getImageManager();

    String uri = getExternalDocument().getSrc();
    Integer firstPageIndex = ImageUtil.getPageIndexFromURI(uri);
    boolean hasPageIndex = (firstPageIndex != null);

    try {
      ImageInfo info = imageManager.getImageInfo(uri, userAgent.getImageSessionContext());

      Object moreImages = info.getCustomObjects().get(ImageInfo.HAS_MORE_IMAGES);
      boolean hasMoreImages = moreImages != null && !Boolean.FALSE.equals(moreImages);

      Dimension intrinsicSize = info.getSize().getDimensionMpt();
      ImageLayout layout = new ImageLayout(getExternalDocument(), this, intrinsicSize);

      PageSequence pageSequence = new PageSequence(null);
      transferExtensions(pageSequence);
      areaTreeHandler.getAreaTreeModel().startPageSequence(pageSequence);
      if (log.isDebugEnabled()) {
        log.debug("Starting layout");
      }

      makePageForImage(info, layout);

      if (!hasPageIndex && hasMoreImages) {
        if (log.isTraceEnabled()) {
          log.trace("Starting multi-page processing...");
        }
        URI originalURI;
        try {
          originalURI = new URI(URISpecification.escapeURI(uri));
          int pageIndex = 1;
          while (hasMoreImages) {
            URI tempURI =
                new URI(
                    originalURI.getScheme(),
                    originalURI.getSchemeSpecificPart(),
                    "page=" + Integer.toString(pageIndex + 1));
            if (log.isTraceEnabled()) {
              log.trace("Subimage: " + tempURI.toASCIIString());
            }
            ImageInfo subinfo =
                imageManager.getImageInfo(
                    tempURI.toASCIIString(), userAgent.getImageSessionContext());

            moreImages = subinfo.getCustomObjects().get(ImageInfo.HAS_MORE_IMAGES);
            hasMoreImages = moreImages != null && !Boolean.FALSE.equals(moreImages);

            intrinsicSize = subinfo.getSize().getDimensionMpt();
            layout = new ImageLayout(getExternalDocument(), this, intrinsicSize);

            makePageForImage(subinfo, layout);

            pageIndex++;
          }
        } catch (URISyntaxException e) {
          getResourceEventProducer().uriError(this, uri, e, getExternalDocument().getLocator());
          return;
        }
      }
    } catch (FileNotFoundException fnfe) {
      getResourceEventProducer().imageNotFound(this, uri, fnfe, getExternalDocument().getLocator());
    } catch (IOException ioe) {
      getResourceEventProducer().imageIOError(this, uri, ioe, getExternalDocument().getLocator());
    } catch (ImageException ie) {
      getResourceEventProducer().imageError(this, uri, ie, getExternalDocument().getLocator());
    }
  }