Example #1
0
  private void doActionRemoveWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "removeWatermark", "source", source);

    if (destination != null && destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    railo.runtime.img.Image ri =
        new railo.runtime.img.Image(1, 1, BufferedImage.TYPE_INT_RGB, Color.BLACK);
    Image img = Image.getInstance(ri.getBufferedImage(), null, false);
    img.setAbsolutePosition(1, 1);

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();

    boolean destIsSource =
        destination != null && doc.getResource() != null && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null) master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {
      int len = reader.getNumberOfPages();
      PdfStamper stamp = new PdfStamper(reader, os);

      Set _pages = doc.getPages();
      for (int i = 1; i <= len; i++) {
        if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue;
        PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0);
        cb.setGState(gs1);
        cb.addImage(img);
      }
      if (bookmarks != null) stamp.setOutlines(master);
      stamp.close();
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name)) {
          pageContext.setVariable(
              name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
        }
      }
    }
  }
Example #2
0
  private void doActionSetInfo() throws PageException, IOException, DocumentException {
    required("pdf", "setInfo", "info", info);
    required("pdf", "getInfo", "source", source);

    PDFDocument doc = toPDFDocument(source, password, null);
    PdfReader pr = doc.getPdfReader();
    OutputStream os = null;
    try {
      if (destination == null) {
        if (doc.getResource() == null)
          throw new ApplicationException(
              "source is not based on a resource, destination file is required");
        destination = doc.getResource();
      } else if (destination.exists() && !overwrite)
        throw new ApplicationException("destination file [" + destination + "] already exists");

      PdfStamper stamp = new PdfStamper(pr, os = destination.getOutputStream());
      HashMap moreInfo = new HashMap();

      Key[] keys = info.keys();
      for (int i = 0; i < keys.length; i++) {
        moreInfo.put(
            StringUtil.ucFirst(keys[i].getLowerString()), Caster.toString(info.get(keys[i])));
      }
      // author
      Object value = info.get("author", null);
      if (value != null) moreInfo.put("Author", Caster.toString(value));
      // keywords
      value = info.get("keywords", null);
      if (value != null) moreInfo.put("Keywords", Caster.toString(value));
      // title
      value = info.get("title", null);
      if (value != null) moreInfo.put("Title", Caster.toString(value));
      // subject
      value = info.get("subject", null);
      if (value != null) moreInfo.put("Subject", Caster.toString(value));
      // creator
      value = info.get("creator", null);
      if (value != null) moreInfo.put("Creator", Caster.toString(value));
      // trapped
      value = info.get("Trapped", null);
      if (value != null) moreInfo.put("Trapped", Caster.toString(value));
      // Created
      value = info.get("Created", null);
      if (value != null) moreInfo.put("Created", Caster.toString(value));
      // Language
      value = info.get("Language", null);
      if (value != null) moreInfo.put("Language", Caster.toString(value));

      stamp.setMoreInfo(moreInfo);
      stamp.close();

    } finally {
      IOUtil.closeEL(os);
      pr.close();
    }
  }
Example #3
0
  private PageContextImpl createPageContext(
      CFMLFactory factory,
      ComponentAccess app,
      String applicationName,
      String cfid,
      Collection.Key methodName)
      throws PageException {
    Resource root = factory.getConfig().getRootDirectory();
    String path = app.getPageSource().getFullRealpath();

    // Request
    HttpServletRequestDummy req =
        new HttpServletRequestDummy(root, "localhost", path, "", null, null, null, null, null);
    if (!StringUtil.isEmpty(cfid))
      req.setCookies(new Cookie[] {new Cookie("cfid", cfid), new Cookie("cftoken", "0")});

    // Response
    OutputStream os = DevNullOutputStream.DEV_NULL_OUTPUT_STREAM;
    try {
      Resource out =
          factory
              .getConfig()
              .getConfigDir()
              .getRealResource("output/" + methodName.getString() + ".out");
      out.getParentResource().mkdirs();
      os = out.getOutputStream(false);
    } catch (IOException e) {
      e.printStackTrace();
      // TODO was passiert hier
    }
    HttpServletResponseDummy rsp = new HttpServletResponseDummy(os);

    // PageContext
    PageContextImpl pc =
        (PageContextImpl)
            factory.getRailoPageContext(factory.getServlet(), req, rsp, null, false, -1, false);
    // ApplicationContext
    ClassicApplicationContext ap =
        new ClassicApplicationContext(
            factory.getConfig(),
            applicationName,
            false,
            app == null ? null : ResourceUtil.getResource(pc, app.getPageSource(), null));
    initApplicationContext(pc, app);
    ap.setName(applicationName);
    ap.setSetSessionManagement(true);
    // if(!ap.hasName())ap.setName("Controler")
    // Base
    pc.setBase(app.getPageSource());

    return pc;
  }
Example #4
0
  private void doActionDeletePages() throws PageException, IOException, DocumentException {
    required("pdf", "deletePage", "pages", pages, true);
    required("pdf", "deletePage", "source", source);

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);

    if (destination == null && StringUtil.isEmpty(name)) {
      if (doc.getResource() == null)
        throw new ApplicationException(
            "source is not based on a resource, destination attribute is required");
      destination = doc.getResource();
    } else if (destination != null && destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    boolean destIsSource =
        destination != null && doc.getResource() != null && destination.equals(doc.getResource());

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {
      PDFUtil.concat(new PDFDocument[] {doc}, os, true, true, true, version);
    } finally {
      // if(document!=null)document.close();
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name)) {
          pageContext.setVariable(
              name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
        }
      }
    }
  }
Example #5
0
  public void install(int index)
      throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {

    X509Certificate cert = tm.chain[index];
    String alias = host + "-" + (index + 1);
    ks.setCertificateEntry(alias, cert);

    OutputStream os = source.getOutputStream();
    try {
      ks.store(os, passphrase);
    } finally {
      IOUtil.closeEL(os);
    }
    /*
        	System.out.println();
        	System.out.println(cert);
        	System.out.println();
        	System.out.println
        		("Added certificate to keystore 'jssecacerts' using alias '"
        		+ alias + "'");
    */
  }
Example #6
0
  private void doActionProtect() throws PageException, IOException, DocumentException {
    required("pdf", "protect", "source", source);

    if (StringUtil.isEmpty(newUserPassword) && StringUtil.isEmpty(newOwnerPassword))
      throw new ApplicationException(
          "at least one of the following attributes must be defined [newUserPassword,newOwnerPassword]");

    PDFDocument doc = toPDFDocument(source, password, null);

    if (destination == null) {
      destination = doc.getResource();
      if (destination == null)
        throw new ApplicationException(
            "source is not based on a resource, destination file is required");
    } else if (destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    boolean destIsSource = doc.getResource() != null && destination.equals(doc.getResource());

    // output
    OutputStream os = null;
    if (destIsSource) {
      os = new ByteArrayOutputStream();
    } else {
      os = destination.getOutputStream();
    }

    try {
      PDFUtil.encrypt(doc, os, newUserPassword, newOwnerPassword, permissions, encrypt);
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        IOUtil.copy(
            new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
            destination,
            true); // MUST overwrite
      }
    }
  }
Example #7
0
  private void doActionWrite() throws PageException, IOException, DocumentException {
    required("pdf", "write", "source", source);
    required("pdf", "write", "destination", destination);

    if (destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    PDFDocument doc = toPDFDocument(source, password, null);
    // PdfReader pr = doc.getPdfReader();
    // output
    boolean destIsSource = doc.getResource() != null && destination.equals(doc.getResource());

    OutputStream os = null;
    if (destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {
      PDFUtil.concat(new PDFDocument[] {doc}, os, true, true, true, version);
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
      }
    }

    /*
    		// flatten = "yes|no"
    	    // must saveOption = "linear|incremental|full"
    */
  }
Example #8
0
  private void doActionMerge()
      throws ApplicationException, PageException, IOException, DocumentException {

    if (source == null && params == null && directory == null)
      throw new ApplicationException(
          "at least one of the following constellation must be defined"
              + " attribute source, attribute directory or cfpdfparam child tags");
    if (destination == null && StringUtil.isEmpty(name, true))
      throw new ApplicationException(
          "at least one of the following attributes must be defined " + "[destination,name]");
    if (destination != null && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    ArrayList docs = new ArrayList();
    PDFDocument doc;
    boolean isListing = false;

    // source
    if (source != null) {
      if (Decision.isArray(source)) {
        Array arr = Caster.toArray(source);
        int len = arr.size();
        for (int i = 1; i <= len; i++) {
          docs.add(doc = toPDFDocument(arr.getE(i), password, null));
          doc.setPages(pages);
        }
      } else if (source instanceof String) {
        String[] sources =
            List.toStringArrayTrim(List.listToArrayRemoveEmpty((String) source, ','));
        for (int i = 0; i < sources.length; i++) {
          docs.add(doc = toPDFDocument(sources[i], password, null));
          doc.setPages(pages);
        }
      } else docs.add(toPDFDocument(source, password, null));
    }
    boolean destIsSource = false;

    // params
    if (directory != null && !directory.isDirectory()) {
      if (!directory.exists())
        throw new ApplicationException("defined attribute directory does not exist");
      throw new ApplicationException("defined attribute directory is not a directory");
    }
    if (params != null) {
      Iterator it = params.iterator();
      PDFParamBean param;
      while (it.hasNext()) {
        param = (PDFParamBean) it.next();
        docs.add(doc = toPDFDocument(param.getSource(), param.getPassword(), directory));
        doc.setPages(param.getPages());
      }
    } else if (directory != null) {
      isListing = true;
      Resource[] children = ResourceUtil.listResources(directory, filter);

      if (ascending) {
        for (int i = children.length - 1; i >= 0; i--) {
          if (destination != null && children[i].equals(destination)) destIsSource = true;
          docs.add(doc = toPDFDocument(children[i], password, null));
          doc.setPages(pages);
        }
      } else {
        for (int i = 0; i < children.length; i++) {
          if (destination != null && children[i].equals(destination)) destIsSource = true;
          docs.add(doc = toPDFDocument(children[i], password, null));
          doc.setPages(pages);
        }
      }
    }

    int doclen = docs.size();
    if (doclen == 0) throw new ApplicationException("you have to define at leat 1 pdf file");

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    /*com.lowagie.text.Document document=null;
    PdfCopy copy=null;
    PdfReader pr;
    Set pages;
    int size;*/

    try {
      if (!isListing) stopOnError = true;
      PDFUtil.concat(
          (PDFDocument[]) docs.toArray(new PDFDocument[docs.size()]),
          os,
          keepBookmark,
          false,
          stopOnError,
          version);
      /*
      boolean init=false;
      for(int d=0;d<doclen;d++) {
      	doc=(PDFDocument) docs.get(d);
      	pages=doc.getPages();
      	try {
      		pr=doc.getPdfReader();
      		print.out(pr.getCatalog().getKeys());

      	}
      	catch(Throwable t) {
      		if(isListing && !stopOnError)continue;
      		throw Caster.toPageException(t);
      	}
      	print.out("d+"+d);
      	if(!init) {
      		init=true;
      		print.out("set");
      		document = new com.lowagie.text.Document(pr.getPageSizeWithRotation(1));
      		copy = new PdfCopy(document,os);
      		document.open();
      	}
      	size=pr.getNumberOfPages();
      	print.out("pages:"+size);
      	for(int page=1;page<=size;page++) {
      		if(pages==null || pages.contains(Constants.Integer(page))) {
      			copy.addPage(copy.getImportedPage(pr, page));
      		}
      	}
      }*/
    } finally {
      // if(document!=null)document.close();
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name))
          pageContext.setVariable(name, ((ByteArrayOutputStream) os).toByteArray());
      }
    }
  }
Example #9
0
  private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
      throw new ApplicationException(
          "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
      throw new ApplicationException("destination file [" + destination + "] already exists");

    // image
    Image img = null;
    if (image != null) {
      railo.runtime.img.Image ri =
          railo.runtime.img.Image.createImage(pageContext, image, false, false, true);
      img = Image.getInstance(ri.getBufferedImage(), null, false);
    }
    // copy From
    else {
      byte[] barr;
      try {
        Resource res = Caster.toResource(pageContext, copyFrom, true);
        barr = IOUtil.toBytes(res);
      } catch (ExpressionException ee) {
        barr = Caster.toBinary(copyFrom);
      }
      img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false);
    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!StringUtil.isEmpty(position)) {
      int index = position.indexOf(',');
      if (index == -1)
        throw new ApplicationException(
            "attribute [position] has a invalid value ["
                + position
                + "],"
                + "value should follow one of the following pattern [40,50], [40,] or [,50]");
      String strX = position.substring(0, index).trim();
      String strY = position.substring(index + 1).trim();
      if (!StringUtil.isEmpty(strX)) x = Caster.toIntValue(strX);
      if (!StringUtil.isEmpty(strY)) y = Caster.toIntValue(strY);
    }

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    boolean destIsSource =
        destination != null && doc.getResource() != null && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null) master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!StringUtil.isEmpty(name) || destIsSource) {
      os = new ByteArrayOutputStream();
    } else if (destination != null) {
      os = destination.getOutputStream();
    }

    try {

      int len = reader.getNumberOfPages();
      PdfStamper stamp = new PdfStamper(reader, os);

      if (len > 0) {
        if (x == UNDEFINED || y == UNDEFINED) {
          PdfImportedPage first = stamp.getImportedPage(reader, 1);
          if (y == UNDEFINED) y = (first.getHeight() - img.getHeight()) / 2;
          if (x == UNDEFINED) x = (first.getWidth() - img.getWidth()) / 2;
        }
        img.setAbsolutePosition(x, y);
        // img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

      }

      // rotation
      if (rotation != 0) {
        img.setRotationDegrees(rotation);
      }

      Set _pages = doc.getPages();
      for (int i = 1; i <= len; i++) {
        if (_pages != null && !_pages.contains(Integer.valueOf(i))) continue;
        PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
        PdfGState gs1 = new PdfGState();
        // print.out("op:"+opacity);
        gs1.setFillOpacity(opacity);
        // gs1.setStrokeOpacity(opacity);
        cb.setGState(gs1);
        cb.addImage(img);
      }
      if (bookmarks != null) stamp.setOutlines(master);
      stamp.close();
    } finally {
      IOUtil.closeEL(os);
      if (os instanceof ByteArrayOutputStream) {
        if (destination != null)
          IOUtil.copy(
              new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
              destination,
              true); // MUST overwrite
        if (!StringUtil.isEmpty(name)) {
          pageContext.setVariable(
              name, new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
        }
      }
    }
  }