@Override
  public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
      throws IOException, ServletException {
    arg2.doFilter(arg0, arg1);

    HttpServletRequest request = (HttpServletRequest) arg0;
    ResponseWrapper response = (ResponseWrapper) arg1;

    if ("doOperation".equals(request.getParameter("method"))
        && "PRINT_ALL_DOCUMENTS".equals(request.getParameter("operationType"))) {

      try {
        // clean the response html and make a DOM document out of it
        String responseHtml = clean(response.getContent());
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(responseHtml.getBytes()));

        // alter paths of link/img tags so itext can use them properly
        patchLinks(doc, request);

        // structure pdf document
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(doc, "");
        renderer.layout();

        // create the pdf
        ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
        renderer.createPDF(pdfStream);

        // concatenate with other docs
        final Person person = (Person) request.getAttribute("person");
        final StudentCandidacy candidacy = getCandidacy(request);
        ByteArrayOutputStream finalPdfStream =
            concatenateDocs(pdfStream.toByteArray(), person, candidacy);
        byte[] pdfByteArray = finalPdfStream.toByteArray();

        // associate the summary file to the candidacy
        associateSummaryFile(pdfByteArray, person.getStudent().getNumber().toString(), candidacy);

        // redirect user to the candidacy summary page
        response.reset();
        response.sendRedirect(buildRedirectURL(request, candidacy));

        response.flushBuffer();
      } catch (ParserConfigurationException e) {
        logger.error(e.getMessage(), e);
      } catch (SAXException e) {
        logger.error(e.getMessage(), e);
      } catch (DocumentException e) {
        logger.error(e.getMessage(), e);
      }
    }
  }
  private boolean encode(ServletOutputStream servletOutputStream, String content) throws Exception {
    try {
      // parse the markup into an xml Document
      final Document doc =
          DocumentBuilderFactory.newInstance()
              .newDocumentBuilder()
              .parse(new InputSource(new StringReader(content)));

      final ITextRenderer renderer = new ITextRenderer();
      renderer.setDocument(doc, null);
      renderer.layout();
      renderer.createPDF(servletOutputStream);
    } finally {
      servletOutputStream.flush();
    }
    return true;
  }
예제 #3
0
  String convert2Pdf(String htmlFileName, String pdfFileName) {
    try {
      String url = new File(htmlFileName).toURI().toURL().toString();
      // Debugging: System.out.println(""+url);
      OutputStream os = new FileOutputStream(pdfFileName);
      ITextRenderer renderer = new ITextRenderer();
      renderer.setDocument(url);
      renderer.layout();
      renderer.createPDF(os);
      os.close();
    } catch (DocumentException e) {
      System.out.println("Error in the html to pdf converter");
    } catch (IOException e) {
      System.out.println("Error in the html to pdf converter");
    } catch (Exception e) {
      System.out.println("Error in the html to pdf converter");
    }

    return pdfFileName;
  }
예제 #4
0
  protected void readInput(
      final PipelineContext pipelineContext,
      final ProcessorInput input,
      Config config,
      OutputStream outputStream) {

    final ExternalContext externalContext = NetUtils.getExternalContext();

    // Read the input as a DOM
    final Document domDocument = readInputAsDOM(pipelineContext, input);

    // Create renderer and add our own callback

    final float DEFAULT_DOTS_PER_POINT = 20f * 4f / 3f;
    final int DEFAULT_DOTS_PER_PIXEL = 14;

    final ITextRenderer renderer =
        new ITextRenderer(DEFAULT_DOTS_PER_POINT, DEFAULT_DOTS_PER_PIXEL);

    // Embed fonts if needed, based on configuration properties
    embedFonts(renderer);

    try {
      final ITextUserAgent callback =
          new ITextUserAgent(renderer.getOutputDevice()) {
            // Called for:
            //
            // - CSS URLs
            // - image URLs
            // - link clicked / form submission (not relevant for our usage)
            // - resolveAndOpenStream below
            public String resolveURI(String uri) {
              // Our own resolver

              // All resources we care about here are resource URLs. The PDF pipeline makes sure
              // that the servlet
              // URL rewriter processes the XHTML output to rewrite resource URLs to absolute paths,
              // including
              // the servlet context and version number if needed. In addition, CSS resources must
              // either use
              // relative paths when pointing to other CSS files or images, or go through the XForms
              // CSS rewriter,
              // which also generates absolute paths.
              // So all we need to do here is rewrite the resulting path to an absolute URL.
              // NOTE: We used to call rewriteResourceURL() here as the PDF pipeline did not do URL
              // rewriting.
              // However this caused issues, for example resources like background images referred
              // by CSS files
              // could be rewritten twice: once by the XForms resource rewriter, and a second time
              // here.
              return URLRewriterUtils.rewriteServiceURL(
                  NetUtils.getExternalContext().getRequest(),
                  uri,
                  ExternalContext.Response.REWRITE_MODE_ABSOLUTE
                      | ExternalContext.Response.REWRITE_MODE_ABSOLUTE_PATH_NO_CONTEXT);
            }

            // Called by:
            //
            // - getCSSResource
            // - getImageResource below
            // - getBinaryResource (not sure when called)
            // - getXMLResource (not sure when called)
            protected InputStream resolveAndOpenStream(String uri) {

              final String resolvedURI = resolveURI(uri);
              // TODO: Use xforms:submission code instead

              // Tell callee we are loading that we are a servlet environment, as in effect we act
              // like
              // a browser retrieving resources directly, not like a portlet. This is the case also
              // if we are
              // called by the proxy portlet or if we are directly within a portlet.
              final Map<String, String[]> headers = new HashMap<String, String[]>();
              headers.put("Orbeon-Client", new String[] {"servlet"});

              final ConnectionResult connectionResult =
                  new Connection()
                      .open(
                          externalContext,
                          new IndentedLogger(logger, ""),
                          false,
                          Connection.Method.GET.name(),
                          URLFactory.createURL(resolvedURI),
                          null,
                          null,
                          null,
                          headers,
                          Connection.getForwardHeaders());

              if (connectionResult.statusCode != 200) {
                connectionResult.close();
                throw new OXFException(
                    "Got invalid return code while loading resource: "
                        + uri
                        + ", "
                        + connectionResult.statusCode);
              }

              pipelineContext.addContextListener(
                  new PipelineContext.ContextListener() {
                    public void contextDestroyed(boolean success) {
                      connectionResult.close();
                    }
                  });

              return connectionResult.getResponseInputStream();
            }

            public ImageResource getImageResource(String uri) {
              final InputStream is = resolveAndOpenStream(uri);
              final String localURI = NetUtils.inputStreamToAnyURI(is, NetUtils.REQUEST_SCOPE);
              return super.getImageResource(localURI);
            }
          };
      callback.setSharedContext(renderer.getSharedContext());
      renderer.getSharedContext().setUserAgentCallback(callback);
      //        renderer.getSharedContext().setDPI(150);

      // Set the document to process
      renderer.setDocument(
          domDocument,
          // No base URL if can't get request URL from context
          externalContext.getRequest() == null
              ? null
              : externalContext.getRequest().getRequestURL());

      // Do the layout and create the resulting PDF
      renderer.layout();
      final List pages = renderer.getRootBox().getLayer().getPages();
      try {
        // Page count might be zero, and if so createPDF
        if (pages != null && pages.size() > 0) {
          renderer.createPDF(outputStream);
        } else {
          // TODO: log?
        }
      } catch (Exception e) {
        throw new OXFException(e);
      } finally {
        try {
          outputStream.close();
        } catch (IOException e) {
          // NOP
          // TODO: log?
        }
      }
    } finally {
      // Free resources associated with the rendering context
      renderer.getSharedContext().reset();
    }
  }