Esempio n. 1
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));
        }
      }
    }
  }
  public void onEndPage(PdfWriter pdfWriter, Document document) {
    pageNum++; // 页面计数
    if (needNotFootAndHead && pageNum >= needNotFootAndHeadPageNum) {
      return;
    }

    PdfContentByte pdfContByte = pdfWriter.getDirectContent();
    pdfContByte.saveState();
    pdfContByte.setGState(pdfGState);
    pdfContByte.setFontAndSize(baseFont, 48);
    pdfContByte.endText();

    Image barCodeImge = code39.createImageWithBarcode(pdfContByte, null, null);

    try {
      pdfContByte.addImage(
          headerImage,
          headerImage.getWidth() / 2,
          0,
          0,
          headerImage.getHeight() / 2,
          document.left() + 65,
          document.top() + 10);
      pdfContByte.addImage(
          barCodeImge,
          barCodeImge.getWidth(),
          0,
          0,
          barCodeImge.getHeight(),
          document.left() + 35,
          document.bottom() - 26);
    } catch (Exception ex) {
      throw new ExceptionConverter(ex);
    }
    pdfContByte.restoreState();
    pdfContByte.saveState();

    String headFootText = "保险合同号:" + this.contNo;
    float headTextPos = document.top() + 10;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 10);
    pdfContByte.setTextMatrix(document.right() - 175, headTextPos);
    pdfContByte.showText(headFootText);
    pdfContByte.endText();
    pdfContByte.saveState();

    //		cell.setBorder(Rectangle.BOTTOM);

    //		String metLife = "中美大都会人寿保险有限公司";
    //		float footTextPos = document.bottom()-12;
    //		pdfContByte.beginText();
    //		pdfContByte.setFontAndSize(baseFont, 7);
    //		pdfContByte.setTextMatrix(document.left()+50, footTextPos);
    //		pdfContByte.showText(metLife);
    //		pdfContByte.endText();
    //		pdfContByte.saveState();

    String shanghaimetLife = "中美联泰大都会人寿保险有限公司";
    float shanghaifootText = document.bottom();
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.left() + 35, shanghaifootText);
    pdfContByte.showText(shanghaimetLife);
    pdfContByte.endText();
    pdfContByte.saveState();

    String shanghaimetLifeAddress = "                  联系地址:上海市黄浦区黄陂北路227号中区广场11楼";
    float shanghaifootTextAddPos = document.bottom();
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 190, shanghaifootTextAddPos);
    pdfContByte.showText(shanghaimetLifeAddress);
    pdfContByte.endText();
    pdfContByte.saveState();

    String metLifeAddress = "北京东城区东长安街一号东方广场东方经贸城东二办公楼12层";
    float footTextAddPos = document.bottom() - 8;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 190, footTextAddPos);
    pdfContByte.showText(metLifeAddress);
    pdfContByte.endText();
    pdfContByte.saveState();

    String metLifeCustSer = "客户服务热线:400 818 8168";
    float footTextCSPos = document.bottom() - 16;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 85, footTextCSPos);
    pdfContByte.showText(metLifeCustSer);
    pdfContByte.endText();
    pdfContByte.saveState();

    String metLifeSite = "http://www.metlife.com.cn/";
    float footTextSTPos = document.bottom() - 24;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 7);
    pdfContByte.setTextMatrix(document.right() - 75, footTextSTPos);
    pdfContByte.showText(metLifeSite);
    pdfContByte.endText();
    pdfContByte.saveState();

    //		String pageNumText = "第 " + pdfWriter.getPageNumber() + " 页";
    String pageNumText = String.valueOf(pdfWriter.getPageNumber());
    float textBase = document.bottom() - 2;
    pdfContByte.beginText();
    pdfContByte.setFontAndSize(baseFont, 9);
    pdfContByte.setTextMatrix(document.left() + 285, textBase);
    pdfContByte.showText(pageNumText);
    pdfContByte.endText();
    pdfContByte.saveState();
  }
Esempio n. 3
0
  public void insertImageRubrica(PdfReader reader, int pageCount, String fileWrite) {
    int iniY = 841 - 10;
    int iniX = 595 - 10;

    try {

      // Verificar qual � a imagem para utilizar na rubrica
      Image img = null;
      if (LoadImageAction.rubimgSameass) img = LoadImageAction.getAssImagePDF();
      else img = LoadImageAction.getRubImagePDF();

      // Criar Modelo para as Rubricas
      ByteArrayOutputStream out = new ByteArrayOutputStream();

      PdfStamper stp1 = new PdfStamper(reader, out, '\3', true);
      PdfFormField sig = PdfFormField.createSignature(stp1.getWriter());

      if (LoadImageAction.posRubSame) {

        int[] coord = LoadImageAction.getImageXY();

        if (!LoadImageAction.posMatriz) { // Se for por coordenadas do sample
          coord[0] = LoadImageAction.getAssX();
          coord[1] = LoadImageAction.getAssY();
        }

        sig.setWidget(
            new Rectangle(
                coord[0], coord[1], coord[0] + img.getWidth(), coord[1] + img.getHeight()),
            null);
      } else {
        sig.setWidget(
            new Rectangle(iniX - img.getWidth(), iniY - img.getHeight(), iniX, iniY), null);
      }

      sig.setFlags(PdfAnnotation.FLAGS_PRINT);
      sig.put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g"));
      sig.setFieldName("Assinaturas");
      sig.setPage(1);

      // Se a imagem da rubrica n for a mesma da assinatura n�o mete na ultima pag
      if (!LoadImageAction.rubimgSameass) pageCount = pageCount - 1;

      // Inserir em todas as paginas o Modelo
      for (int i = 1; i <= pageCount; i++) stp1.addAnnotation(sig, i);

      stp1.close();

      // Guardar/Ler PDF com modelos inseridos
      reader = new PdfReader(out.toByteArray());
      File outputFile = new File(fileWrite);

      // Preencher Modelo com Dados
      PdfStamper stp = PdfStamper.createSignature(reader, null, '\0', outputFile, true);

      PdfSignatureAppearance sap = stp.getSignatureAppearance();
      sap.setAcro6Layers(true);
      reader.close();
      sap.setVisibleSignature("Assinaturas");
      sap.setLayer2Text("\n\n(Doc. assinado digitalmente)");
      sap.setImage(img);
      PdfSignature dic =
          new PdfSignature(
              PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); // $NON-NLS-1$
      dic.setReason(sap.getReason());
      dic.setLocation(sap.getLocation());
      dic.setContact(sap.getContact());
      dic.setDate(new PdfDate(sap.getSignDate()));
      sap.setCryptoDictionary(dic);
      int contentEstimated = 15000;
      HashMap<Object, Object> exc = new HashMap<Object, Object>();
      exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
      sap.preClose(exc);

      Provider prov = entry.getProvider();
      PrivateKey key = entry.getPrivateKey();
      Certificate[] chain = entry.getCertificateChain();
      PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", prov.getName(), false); // $NON-NLS-1$
      InputStream data = sap.getRangeStream();
      MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); // $NON-NLS-1$
      byte buf[] = new byte[8192];
      int n;
      while ((n = data.read(buf)) > 0) {
        messageDigest.update(buf, 0, n);
      }
      byte hash[] = messageDigest.digest();
      Calendar cal = Calendar.getInstance();
      byte[] ocsp = null;

      if (isUseOCSP() && chain.length >= 2) {
        String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
        if (url != null && url.length() > 0)
          ocsp =
              new OcspClientBouncyCastle(
                      (X509Certificate) chain[0], (X509Certificate) chain[1], url)
                  .getEncoded();
      }
      byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
      sgn.update(sh, 0, sh.length);

      TSAClient tsc = null;
      if (isUseTSA() && tsaLocation != null) tsc = new TSAClientBouncyCastle(tsaLocation);
      byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);

      if (contentEstimated + 2 < encodedSig.length)
        throw new Exception("Not enough space"); // $NON-NLS-1$

      byte[] paddedSig = new byte[contentEstimated];
      PdfDictionary dic2 = new PdfDictionary();
      System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
      dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
      sap.close(dic2);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 4
0
 private void setPaint(boolean invert, double xoffset, double yoffset, boolean fill) {
   if (paint instanceof Color) {
     Color color = (Color) paint;
     int alpha = color.getAlpha();
     if (fill) {
       if (alpha != currentFillGState) {
         currentFillGState = alpha;
         PdfGState gs = fillGState[alpha];
         if (gs == null) {
           gs = new PdfGState();
           gs.setFillOpacity(alpha / 255f);
           fillGState[alpha] = gs;
         }
         cb.setGState(gs);
       }
       cb.setColorFill(color);
     } else {
       if (alpha != currentStrokeGState) {
         currentStrokeGState = alpha;
         PdfGState gs = strokeGState[alpha];
         if (gs == null) {
           gs = new PdfGState();
           gs.setStrokeOpacity(alpha / 255f);
           strokeGState[alpha] = gs;
         }
         cb.setGState(gs);
       }
       cb.setColorStroke(color);
     }
   } else if (paint instanceof GradientPaint) {
     GradientPaint gp = (GradientPaint) paint;
     Point2D p1 = gp.getPoint1();
     transform.transform(p1, p1);
     Point2D p2 = gp.getPoint2();
     transform.transform(p2, p2);
     Color c1 = gp.getColor1();
     Color c2 = gp.getColor2();
     PdfShading shading =
         PdfShading.simpleAxial(
             cb.getPdfWriter(),
             (float) p1.getX(),
             normalizeY((float) p1.getY()),
             (float) p2.getX(),
             normalizeY((float) p2.getY()),
             c1,
             c2);
     PdfShadingPattern pat = new PdfShadingPattern(shading);
     if (fill) cb.setShadingFill(pat);
     else cb.setShadingStroke(pat);
   } else if (paint instanceof TexturePaint) {
     try {
       TexturePaint tp = (TexturePaint) paint;
       BufferedImage img = tp.getImage();
       Rectangle2D rect = tp.getAnchorRect();
       com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img, null);
       PdfPatternPainter pattern = cb.createPattern(image.getWidth(), image.getHeight());
       AffineTransform inverse = this.normalizeMatrix();
       inverse.translate(rect.getX(), rect.getY());
       inverse.scale(rect.getWidth() / image.getWidth(), -rect.getHeight() / image.getHeight());
       double[] mx = new double[6];
       inverse.getMatrix(mx);
       pattern.setPatternMatrix(
           (float) mx[0],
           (float) mx[1],
           (float) mx[2],
           (float) mx[3],
           (float) mx[4],
           (float) mx[5]);
       image.setAbsolutePosition(0, 0);
       pattern.addImage(image);
       if (fill) cb.setPatternFill(pattern);
       else cb.setPatternStroke(pattern);
     } catch (Exception ex) {
       if (fill) cb.setColorFill(Color.gray);
       else cb.setColorStroke(Color.gray);
     }
   } else {
     try {
       BufferedImage img = null;
       int type = BufferedImage.TYPE_4BYTE_ABGR;
       if (paint.getTransparency() == Transparency.OPAQUE) {
         type = BufferedImage.TYPE_3BYTE_BGR;
       }
       img = new BufferedImage((int) width, (int) height, type);
       Graphics2D g = (Graphics2D) img.getGraphics();
       g.transform(transform);
       AffineTransform inv = transform.createInverse();
       Shape fillRect = new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight());
       fillRect = inv.createTransformedShape(fillRect);
       g.setPaint(paint);
       g.fill(fillRect);
       if (invert) {
         AffineTransform tx = new AffineTransform();
         tx.scale(1, -1);
         tx.translate(-xoffset, -yoffset);
         g.drawImage(img, tx, null);
       }
       g.dispose();
       g = null;
       com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(img, null);
       PdfPatternPainter pattern = cb.createPattern(width, height);
       image.setAbsolutePosition(0, 0);
       pattern.addImage(image);
       if (fill) cb.setPatternFill(pattern);
       else cb.setPatternStroke(pattern);
     } catch (Exception ex) {
       if (fill) cb.setColorFill(Color.gray);
       else cb.setColorStroke(Color.gray);
     }
   }
 }
Esempio n. 5
0
  public String hashSignExternalTimestamp(String read, String write) throws Exception {
    Provider prov = entry.getProvider();
    PrivateKey key = entry.getPrivateKey();
    Certificate[] chain = entry.getCertificateChain();

    PdfReader reader = new PdfReader(read);
    int pageCount = reader.getNumberOfPages();

    File outputFile = new File(write);
    PdfStamper stp = PdfStamper.createSignature(reader, null, '\0', outputFile, true);

    PdfSignatureAppearance sap = stp.getSignatureAppearance();
    sap.setProvider(prov.getName());
    sap.setReason(getReason());
    sap.setLocation(getLocation());
    sap.setContact(getContact());

    sap.setCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED);

    int[] coord = LoadImageAction.getImageXY();

    if (!LoadImageAction.posMatriz) { // Se for por coordenadas do sample
      coord[0] = LoadImageAction.getAssX();
      coord[1] = LoadImageAction.getAssY();
    }

    // Adicionar imagem ao PDF se for para utilizar
    if (!isSignatureVisible()) {
      sap.setLayer2Text("");
    } else {
      if (LoadImageAction.getFlagPDF()) {
        sap.setAcro6Layers(true);
        Image img = LoadImageAction.getAssImagePDF();

        if (LoadImageAction.getPagToSign() == -1)
          sap.setVisibleSignature(
              new Rectangle(
                  coord[0], coord[1], coord[0] + img.getWidth(), coord[1] + img.getHeight()),
              pageCount,
              null);
        else
          sap.setVisibleSignature(
              new Rectangle(
                  coord[0], coord[1], coord[0] + img.getWidth(), coord[1] + img.getHeight()),
              LoadImageAction.getPagToSign(),
              null);

        sap.setLayer2Text("\n\n(Doc. assinado digitalmente)");
        sap.setImage(img);
      } else {
        if (LoadImageAction.getPagToSign() == -1)
          sap.setVisibleSignature(
              new Rectangle(coord[0], coord[1], coord[0] + 150, coord[1] + 40), pageCount, null);
        else
          sap.setVisibleSignature(
              new Rectangle(coord[0], coord[1], coord[0] + 150, coord[1] + 40),
              LoadImageAction.getPagToSign(),
              null);

        sap.setLayer2Text(getSignatureText((X509Certificate) chain[0], sap.getSignDate()));
      }
    }

    PdfSignature dic =
        new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); // $NON-NLS-1$
    dic.setReason(sap.getReason());
    dic.setLocation(sap.getLocation());
    dic.setContact(sap.getContact());
    dic.setDate(new PdfDate(sap.getSignDate()));
    sap.setCryptoDictionary(dic);
    int contentEstimated = 15000;
    HashMap<Object, Object> exc = new HashMap<Object, Object>();
    exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
    sap.preClose(exc);

    PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", prov.getName(), false);
    InputStream data = sap.getRangeStream();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); // $NON-NLS-1$
    byte buf[] = new byte[8192];
    int n;
    while ((n = data.read(buf)) > 0) {
      messageDigest.update(buf, 0, n);
    }
    byte hash[] = messageDigest.digest();
    Calendar cal = Calendar.getInstance();
    byte[] ocsp = null;
    if (isUseOCSP() && chain.length >= 2) {
      String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
      if (url != null && url.length() > 0)
        ocsp =
            new OcspClientBouncyCastle((X509Certificate) chain[0], (X509Certificate) chain[1], url)
                .getEncoded();
    }
    byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
    sgn.update(sh, 0, sh.length);
    TSAClient tsc = null;
    if (isUseTSA() && tsaLocation != null) tsc = new TSAClientBouncyCastle(tsaLocation);

    // o PIN/PASS dos certificados � pedido aqui
    byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);

    if (contentEstimated + 2 < encodedSig.length)
      throw new Exception("Not enough space"); // $NON-NLS-1$

    byte[] paddedSig = new byte[contentEstimated];
    System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
    PdfDictionary dic2 = new PdfDictionary();
    dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
    sap.close(dic2);

    deleteFile(read);
    return write;
  }