Exemplo n.º 1
0
 public static PdfStamper createSignature(
     PdfReader reader, OutputStream os, char pdfVersion, File tempFile, boolean append)
     throws DocumentException, IOException {
   PdfStamper stp;
   if (tempFile == null) {
     ByteBuffer bout = new ByteBuffer();
     stp = new PdfStamper(reader, bout, pdfVersion, append);
     stp.sigApp = new PdfSignatureAppearance(stp.stamper);
     stp.sigApp.setSigout(bout);
   } else {
     if (tempFile.isDirectory()) tempFile = File.createTempFile("pdf", null, tempFile);
     FileOutputStream fout = new FileOutputStream(tempFile);
     stp = new PdfStamper(reader, fout, pdfVersion, append);
     stp.sigApp = new PdfSignatureAppearance(stp.stamper);
     stp.sigApp.setTempFile(tempFile);
   }
   stp.sigApp.setOriginalout(os);
   stp.sigApp.setStamper(stp);
   stp.hasSignature = true;
   PdfDictionary catalog = reader.getCatalog();
   PdfDictionary acroForm =
       (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.ACROFORM), catalog);
   if (acroForm != null) {
     acroForm.remove(PdfName.NEEDAPPEARANCES);
     stp.stamper.markUsed(acroForm);
   }
   return stp;
 }
    public ByteArrayOutputStream getFilledPdf(Person person) throws IOException, DocumentException {
      InputStream istream = getClass().getResourceAsStream(BPI_AEIST_CARD_PDF_PATH);
      PdfReader reader = new PdfReader(istream);
      reader.getAcroForm().remove(PdfName.SIGFLAGS);
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      PdfStamper stamper = new PdfStamper(reader, output);
      form = stamper.getAcroFields();

      setField("BI/CC", person.getDocumentIdNumber());
      setField("Nome", person.getName());
      setField(
          "topmostSubform[0].Page1[0].Datavalidade[0]",
          person
              .getExpirationDateOfDocumentIdYearMonthDay()
              .toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
      setField(
          "dia",
          String.valueOf(person.getExpirationDateOfDocumentIdYearMonthDay().getDayOfMonth()));
      setField(
          "Mês",
          String.valueOf(person.getExpirationDateOfDocumentIdYearMonthDay().getMonthOfYear()));
      setField("Ano", String.valueOf(person.getExpirationDateOfDocumentIdYearMonthDay().getYear()));

      LocalDate today = new LocalDate();
      setField("dia_1", String.valueOf(today.getDayOfMonth()));
      setField("Mês_1", String.valueOf(today.getMonthOfYear()));
      setField("Ano_1", String.valueOf(today.getYear()));

      stamper.setFormFlattening(true);
      stamper.close();
      return output;
    }
Exemplo n.º 3
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));
        }
      }
    }
  }
Exemplo n.º 4
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();
    }
  }
    public ByteArrayOutputStream getFilledPdf(Person person) throws IOException, DocumentException {
      InputStream istream = getClass().getResourceAsStream(BPI_PERSONAL_INFORMATION_PDF_PATH);
      PdfReader reader = new PdfReader(istream);
      reader.getAcroForm().remove(PdfName.SIGFLAGS);
      reader.selectPages("1,2");
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      PdfStamper stamper = new PdfStamper(reader, output);
      form = stamper.getAcroFields();

      setField("Nome completo_1", person.getName());
      setField("NIF", person.getSocialSecurityNumber());
      setField("Nº", person.getDocumentIdNumber());

      setField("Nacionalidade", person.getCountryOfBirth().getCountryNationality().toString());
      setField("Naturalidade", person.getCountryOfBirth().getName());

      setField("Distrito", person.getDistrictOfBirth());
      setField("Concelho", person.getDistrictSubdivisionOfBirth());
      setField("Freguesia", person.getParishOfBirth());
      setField("Nome do Pai", person.getNameOfFather());
      setField("Nome da Mãe", person.getNameOfMother());
      setField("Morada de Residencia_1", person.getAddress());
      setField("Localidade", person.getAreaOfAreaCode());
      setField("Designação Postal", person.getAreaOfAreaCode());
      setField("País", person.getCountryOfResidence().getName());

      String postalCode = person.getPostalCode();
      int dashIndex = postalCode.indexOf('-');
      setField("Código Postal4", postalCode.substring(0, 4));
      String last3Numbers = postalCode.substring(dashIndex + 1, dashIndex + 4);
      setField("Código Postal_5", last3Numbers);
      setField("Móvel", person.getDefaultMobilePhoneNumber());
      setField("E-mail", getMail(person));

      YearMonthDay emissionDate = person.getEmissionDateOfDocumentIdYearMonthDay();
      if (emissionDate != null) {
        setField("Dia_1", String.valueOf(emissionDate.getDayOfMonth()));
        setField("Mês_1", String.valueOf(emissionDate.getMonthOfYear()));
        setField("Ano_1", String.valueOf(emissionDate.getYear()));
      }

      YearMonthDay expirationDate = person.getExpirationDateOfDocumentIdYearMonthDay();
      setField("Dia_2", String.valueOf(expirationDate.getDayOfMonth()));
      setField("Mês_2", String.valueOf(expirationDate.getMonthOfYear()));
      setField("Ano_2", String.valueOf(expirationDate.getYear()));

      YearMonthDay birthdayDate = person.getDateOfBirthYearMonthDay();
      setField("Dia3", String.valueOf(birthdayDate.getDayOfMonth()));
      setField("Mês3", String.valueOf(birthdayDate.getMonthOfYear()));
      setField("Ano_3", String.valueOf(birthdayDate.getYear()));

      stamper.setFormFlattening(true);
      stamper.close();
      return output;
    }
Exemplo n.º 6
0
  public static void main(String[] args) throws Exception {
    String filePath = ReaderPdf.class.getClassLoader().getResource("pdf/pdf.pdf").getPath();

    // 待加水印的文件
    PdfReader reader = new PdfReader(filePath);

    String newFilePath = "D:/test/newPdf.pdf";
    File f = new File(newFilePath);
    if (!f.exists()) {
      f.createNewFile();
    }

    // 加完水印的文件
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(newFilePath));
    int total = reader.getNumberOfPages() + 1;

    PdfContentByte content;
    // 设置字体
    BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

    // BaseFont baseFont =
    // BaseFont.createFont("STSong-Light",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
    // BaseFont baseFont =
    // BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
    // 水印文字
    String waterText = "------广东省云浮市闻莺路东升布艺------";
    int leng = waterText.length(); // 文字长度
    char c = 0;
    int height = 0; // 高度
    // 循环对每页插入水印
    for (int i = 1; i < total; i++) {
      // 水印的起始
      height = 500;
      content = stamper.getUnderContent(i);
      // 开始
      content.beginText();
      // 设置颜色
      content.setColorFill(Color.GRAY);
      // 设置字体及字号
      content.setFontAndSize(baseFont, 18);
      // 设置起始位置
      content.setTextMatrix(500, 780);
      // 开始写入水印
      for (int k = 0; k < leng; k++) {
        content.setTextRise(14);
        c = waterText.charAt(k);
        // 将char转成字符串
        content.showText(c + "");
        height -= 5;
      }
      content.endText();
    }
    stamper.close();
  }
Exemplo n.º 7
0
 /**
  * Merges an XFDF file with a PDF form.
  *
  * @param args no arguments needed
  */
 public static void main(String[] args) {
   try {
     // merging the FDF file
     PdfReader pdfreader = new PdfReader("SimpleRegistrationForm.pdf");
     PdfStamper stamp = new PdfStamper(pdfreader, new FileOutputStream("registered_xfdf.pdf"));
     XfdfReader fdfreader = new XfdfReader("register.xfdf");
     AcroFields form = stamp.getAcroFields();
     form.setFields(fdfreader);
     stamp.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
    public ByteArrayOutputStream getFilledPdf(Person person) throws IOException, DocumentException {
      InputStream istream = getClass().getResourceAsStream(BPI_PRODUCTS_SERVICES_PDF_PATH);
      PdfReader reader = new PdfReader(istream);
      reader.getAcroForm().remove(PdfName.SIGFLAGS);
      reader.selectPages("1");
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      PdfStamper stamper = new PdfStamper(reader, output);
      form = stamper.getAcroFields();

      setField("Nome_1", person.getName());
      stamper.setFormFlattening(true);
      stamper.close();
      return output;
    }
Exemplo n.º 9
0
  /**
   * Main.
   *
   * @param args
   * @throws Exception
   */
  public static void main(final String[] args) throws Exception {

    // PDF de ejemplo
    final PdfReader reader =
        new PdfReader(
            AOUtil.getDataFromInputStream(
                ClassLoader.getSystemResourceAsStream("TEST_PDF.pdf") // $NON-NLS-1$
                ));
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final Calendar globalDate = new GregorianCalendar();
    final PdfStamper stamper = new PdfStamper(reader, baos, globalDate);

    //		// Datos a insertar como XMP
    //		final BioMetadataSchema schema = new BioMetadataSchema();
    //		schema.addIso197947Data("HOLA".getBytes()); //$NON-NLS-1$
    //
    //		// Insertamos los datos en el XMP
    //		final ByteArrayOutputStream os = new ByteArrayOutputStream();
    //        final XmpWriter xmp = new XmpWriter(os);
    //        xmp.addRdfDescription(schema);
    //        xmp.close();
    //
    //        // Insertamos el XMP en el PDF
    //        stamper.setXmpMetadata(os.toByteArray());

    final String sigDataBase64 =
        Base64.encode(
            AOUtil.getDataFromInputStream(
                ClassLoader.getSystemResourceAsStream("4df6ec6b6b5c7.jpg") // $NON-NLS-1$
                ));
    final HashMap<String, String> moreInfo = new HashMap<String, String>(1);
    moreInfo.put("SignerBiometricSignatureData", sigDataBase64); // $NON-NLS-1$
    moreInfo.put("SignerBiometricSignatureFormat", "ISO 19795-7"); // $NON-NLS-1$ //$NON-NLS-2$
    moreInfo.put("SignerName", "Tom\u00E1s Garc\u00EDa-Mer\u00E1s"); // $NON-NLS-1$ //$NON-NLS-2$
    stamper.setMoreInfo(moreInfo);

    stamper.close(globalDate);
    reader.close();

    // Guardamos el resultado
    final File tmpFile = File.createTempFile("TESTXMP_", ".pdf"); // $NON-NLS-1$ //$NON-NLS-2$
    final OutputStream fos = new FileOutputStream(tmpFile);
    fos.write(baos.toByteArray());
    fos.flush();
    fos.close();
  }
    public ByteArrayOutputStream getFilledPdf(Person person, StudentCandidacy candidacy)
        throws IOException, DocumentException {
      InputStream istream = getClass().getResourceAsStream(SANTANDER_APPLICATION_CARD_PDF_PATH);
      PdfReader reader = new PdfReader(istream);
      reader.getAcroForm().remove(PdfName.SIGFLAGS);
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      PdfStamper stamper = new PdfStamper(reader, output);
      form = stamper.getAcroFields();

      setField("StudentIdentification", person.getIstUsername());
      setField("Phone", person.getDefaultMobilePhoneNumber());
      setField("Email", getMail(person));
      setField(
          "CurrentDate", new DateTime().toString(DateTimeFormat.forPattern("dd/MM/yyyy HH:mm")));

      SantanderPhotoEntry photoEntryForPerson =
          SantanderPhotoEntry.getOrCreatePhotoEntryForPerson(
              candidacy.getRegistration().getPerson());
      if (photoEntryForPerson != null) {
        setField("Sequence", photoEntryForPerson.getPhotoIdentifier());

        try {
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          BarcodeImageHandler.writeJPEG(
              BarcodeFactory.createCode39(photoEntryForPerson.getPhotoIdentifier(), false), baos);
          Jpeg sequenceBarcodeImg = new Jpeg(baos.toByteArray());
          float[] sequenceFieldPositions =
              form.getFieldPositions(
                  "SequenceBarcode"); // 1-lowerleftX, 2-lly, 3-upperRightX, 4-ury
          sequenceBarcodeImg.setAbsolutePosition(
              sequenceFieldPositions[1], sequenceFieldPositions[2]);
          sequenceBarcodeImg.scalePercent(45);
          stamper.getOverContent(1).addImage(sequenceBarcodeImg);
        } catch (OutputException e) {
          logger.error(e.getMessage(), e);
        } catch (BarcodeException be) {
          logger.error(be.getMessage(), be);
        }

        Jpeg photo = new Jpeg(photoEntryForPerson.getPhotoAsByteArray());
        float[] photoFieldPositions =
            form.getFieldPositions("Photo"); // 1-lowerleftX, 2-lly, 3-upperRightX, 4-ury
        photo.setAbsolutePosition(photoFieldPositions[1], photoFieldPositions[2]);
        photo.scalePercent(95);
        stamper.getOverContent(1).addImage(photo);
      }

      try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BarcodeImageHandler.writeJPEG(BarcodeFactory.createCode128(person.getIstUsername()), baos);
        Jpeg studentIdBarcodeImg = new Jpeg(baos.toByteArray());
        float[] studentIdFieldPositions =
            form.getFieldPositions(
                "StudentIdentificationBarcode"); // 1-lowerleftX, 2-lly, 3-upperRightX, 4-ury
        studentIdBarcodeImg.setAbsolutePosition(
            studentIdFieldPositions[1], studentIdFieldPositions[2]);
        studentIdBarcodeImg.scalePercent(45);
        stamper.getOverContent(1).addImage(studentIdBarcodeImg);
      } catch (OutputException e) {
        logger.error(e.getMessage(), e);
      } catch (BarcodeException be) {
        logger.error(be.getMessage(), be);
      }

      stamper.setFormFlattening(true);
      stamper.close();
      return output;
    }
Exemplo n.º 11
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));
        }
      }
    }
  }
Exemplo n.º 12
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();
    }
  }
Exemplo n.º 13
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;
  }
Exemplo n.º 14
0
  /** 入力票の項目を作成する */
  public File printKekka() {
    /* Modified 2008/07/25 若月  */
    /* --------------------------------------------------- */
    //		templatePath = PropertyUtil.getProperty("filePath");
    //		outputPath = PropertyUtil.getProperty("filePath");
    //		templatePath = templatePath + infilename;
    //		outputPath = ".\\Data\\PDF\\" + outfilename;
    /* --------------------------------------------------- */
    PropertyUtil util = new PropertyUtil(JPath.PATH_FILE_PROPERTIES);

    templatePath = util.getProperty("filePath");
    outputPath = templatePath;
    templatePath = templatePath + infilename;
    /* --------------------------------------------------- */
    /* Modified 2008/09/11 薮  */
    /* --------------------------------------------------- */
    //		outputPath = ".\\Data\\PDF\\" + outfilename;
    outputPath =
        "." + File.separator + "Data" + File.separator + "PDF" + File.separator + "" + outfilename;
    /* --------------------------------------------------- */

    /* --------------------------------------------------- */
    /* Modified 2008/09/11 薮  */
    /* --------------------------------------------------- */
    //		File outfile = new File(".\\Data\\PDF");
    File outfile = new File("." + File.separator + "Data" + File.separator + "PDF");
    /* --------------------------------------------------- */
    outfile.mkdirs();

    // File n = new File(".\\Data\\PDF\\outNyuryokuTemplate.pdf");
    File file = null;
    try {
      /*
       * 個人情報 PrintDataから個人情報を抽出
       */
      Kojin tmpKojin = (Kojin) printData.get("Kojin");
      Hashtable<String, String> kojinData = tmpKojin.getPrintKojinData();

      /* --------------------------------------------------- */
      /* Added 2008/09/11 薮  */
      /* --------------------------------------------------- */
      String strKensaYmd = "";
      if (kojinData.get("KENSA_NENGAPI") == null) {
        // edit stop s.inoue 2009/10/15
        // strKensaYmd = String.valueOf(FiscalYearUtil.getSystemDate());
        // edit s.inoue 2009/10/16
        // strKensaYmd = null;
        strKensaYmd = getKenshinDate();
      } else {
        strKensaYmd = replaseNenGaPii(kojinData.get("KENSA_NENGAPI"));
        //				strKensaYmd = kojinData.get("KENSA_NENGAPI").replaceAll("[^0-9]+","");
      }

      // ファイル作成
      PdfReader reader = new PdfReader(templatePath);
      PdfStamper stamp =
          new PdfStamper(
              reader,
              new FileOutputStream(
                  outputPath
                      + kojinData.get("UKETUKE_ID")
                      /* --------------------------------------------------- */
                      /* Modified 2008/09/11 薮  */
                      /* --------------------------------------------------- */
                      //							+ kojinData.get("KENSA_NENGAPI")));
                      + strKensaYmd));
      /* --------------------------------------------------- */
      AcroFields form = stamp.getAcroFields();

      /* --------------------------------------------------- */
      /* Modified 2008/09/11 薮  */
      /* --------------------------------------------------- */
      //			file = new File(".\\Data\\PDF\\" + outfilename

      file =
          new File(
              "."
                  + File.separator
                  + "Data"
                  + File.separator
                  + "PDF"
                  + File.separator
                  + ""
                  + outfilename
                  + kojinData.get("UKETUKE_ID")
                  //					+ kojinData.get("KENSA_NENGAPI"));
                  + strKensaYmd);
      /* --------------------------------------------------- */

      // 健診年月日
      form.setField("T1", kojinData.get("KENSA_NENGAPI"));
      form.setField("T19", kojinData.get("KENSA_NENGAPI"));
      // 受診券番号
      form.setField("T2", kojinData.get("JYUSHIN_SEIRI_NO"));
      form.setField("T20", kojinData.get("JYUSHIN_SEIRI_NO"));
      // 保険者番号
      form.setField("T3", kojinData.get("HKNJANUM"));
      form.setField("T21", kojinData.get("HKNJANUM"));
      // 被保険者証等記号
      form.setField("T4", kojinData.get("HIHOKENJYASYO_KIGOU"));
      form.setField("T22", kojinData.get("HIHOKENJYASYO_KIGOU"));
      // 被保険者証等番号
      form.setField("T5", kojinData.get("HIHOKENJYASYO_NO"));
      form.setField("T23", kojinData.get("HIHOKENJYASYO_NO"));
      // フリガナ
      form.setField("T6", kojinData.get("KANANAME"));
      form.setField("T24", kojinData.get("KANANAME"));
      // 氏名
      form.setField("T7", kojinData.get("NAME"));
      form.setField("T26", kojinData.get("NAME"));

      // 生年月日
      form.setField("T8", kojinData.get("BIRTHDAY"));
      form.setField("T25", kojinData.get("BIRTHDAY"));

      // 性別
      form.setField("T9", kojinData.get("SEX"));
      form.setField("T27", kojinData.get("SEX"));

      // 年齢
      form.setField("T10", kojinData.get("AGE"));
      form.setField("T28", kojinData.get("AGE"));

      // del s.inoue 2009/11/16
      //			if (kojinData.get("UKETUKE_ID") != null) {
      //				Hashtable<String, String> ResultItem = null;
      //				// 追加の項目
      //				// 項目名
      //				int setCnt = 11;
      //				List tuika = this.tuika(kojinData);
      //				int tuikaSize = tuika.size();
      //
      //				if (tuikaSize > 0) {
      //					for (int i = 0; i < tuikaSize; i++) {
      //						ResultItem = (Hashtable<String, String>) tuika.get(i);
      //						form.setField("S" + Integer.toString(setCnt),
      //								ResultItem.get("KOUMOKU_NAME"));
      //						setCnt++;
      //					}
      //				}
      //
      //				// 項目名
      //				int setTani = 19;
      //				if (tuikaSize > 0) {
      //					for (int i = 0; i < tuikaSize; i++) {
      //						ResultItem = (Hashtable<String, String>) tuika.get(i);
      //						form.setField("S" + Integer.toString(setTani),
      //								ResultItem.get("TANI"));
      //						setTani++;
      //					}
      //				}
      //
      //			}

      stamp.setFormFlattening(true);
      stamp.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return file;
  }
  @Override
  public String create() {

    try {
      Document document =
          new Document(
              PageSize.A4, getMarginLeft(), getMarginRight(), getMarginTop(), getMarginBottom());

      String path =
          UserDocumentHelper.createPathToDocument(
              getDocumentDir(), // PDF File を置く場所
              "診断書", // 文書名
              EXT_PDF, // 拡張子
              model.getPatientName(), // 患者氏名
              new Date()); // 日付
      // minagawa^ jdk7
      Path pathObj = Paths.get(path);
      setPathToPDF(pathObj.toAbsolutePath().toString()); // 呼び出し側で取り出せるように保存する
      // minagawa$
      // Open Document
      ByteArrayOutputStream byteo = new ByteArrayOutputStream();
      PdfWriter.getInstance(document, byteo);
      document.open();

      // Font
      baseFont = BaseFont.createFont(HEISEI_MIN_W3, UNIJIS_UCS2_HW_H, false);
      if (Project.getString(Project.SHINDANSYO_FONT_SIZE).equals("small")) {
        titleFont = new Font(baseFont, getTitleFontSize());
        bodyFont = new Font(baseFont, getBodyFontSize());
      } else {
        titleFont = new Font(baseFont, 18);
        bodyFont = new Font(baseFont, 14);
      }

      // ----------------------------------------
      // タイトル
      // ----------------------------------------
      Paragraph para = new Paragraph(DOC_TITLE, titleFont);
      para.setAlignment(Element.ALIGN_CENTER);
      document.add(para);
      document.add(new Paragraph(" "));
      document.add(new Paragraph(" "));
      document.add(new Paragraph(" "));

      // ----------------------------------------
      // 患者情報テーブル
      // ----------------------------------------
      PdfPTable pTable = new PdfPTable(new float[] {20.0f, 60.0f, 10.0f, 10.0f});
      pTable.setWidthPercentage(100.0f);

      // 患者氏名
      PdfPCell cell;
      pTable.addCell(createNoBorderCell("氏  名"));
      cell = createNoBorderCell(model.getPatientName());
      cell.setColspan(3);
      pTable.addCell(cell);

      // 生年月日 性別
      pTable.addCell(createNoBorderCell("生年月日"));
      pTable.addCell(createNoBorderCell(getDateString(model.getPatientBirthday())));
      pTable.addCell(createNoBorderCell("性別"));
      pTable.addCell(createNoBorderCell(model.getPatientGender()));

      // 住所
      pTable.addCell(createNoBorderCell("住  所"));
      cell = createNoBorderCell(model.getPatientAddress());
      cell.setColspan(3);
      pTable.addCell(cell);

      // 傷病名
      String disease = model.getItemValue(MedicalCertificateImpl.ITEM_DISEASE);
      pTable.addCell(createNoBorderCell("傷 病 名"));
      cell = createNoBorderCell(disease);
      cell.setColspan(3);
      pTable.addCell(cell);

      document.add(pTable);
      document.add(new Paragraph(" "));

      // ------------------------------------------
      // コンテントテーブル
      // ------------------------------------------
      pTable = new PdfPTable(new float[] {1.0f});
      pTable.setWidthPercentage(100.0f);
      String informed = model.getTextValue(MedicalCertificateImpl.TEXT_INFORMED_CONTENT);
      cell = createNoBorderCell(informed);
      if (Project.getString("sindansyo.font.size").equals("small")) {
        cell.setFixedHeight(250.0f); // Cell 高
      } else {
        cell.setFixedHeight(225.0f); // Cell 高
      }
      cell.setLeading(0f, 1.5f); // x 1.5 font height
      pTable.addCell(cell);
      document.add(pTable);
      document.add(new Paragraph(" "));

      // ------------------------------------------
      // 署名テーブル
      // ------------------------------------------
      // 日付
      pTable = new PdfPTable(new float[] {1.0f});
      pTable.setWidthPercentage(100.0f);

      // 上記の通り診断する
      pTable.addCell(createNoBorderCell("上記の通り診断する。"));
      // minagawa^ LSC 1.4 bug fix 文書の印刷日付 2013/06/24
      // String dateStr = getDateString(model.getConfirmed());
      String dateStr = getDateString(model.getStarted());
      // minagawa$
      pTable.addCell(createNoBorderCell(dateStr));

      // 住所 BaseFont.getWidthPoint
      String zipCode = model.getConsultantZipCode();
      String address = model.getConsultantAddress();
      //            float zipLen = baseFont.getWidthPoint(zipCode, 12.0f);
      //            float addressLen = baseFont.getWidthPoint(address, 12.0f);
      //            float padlen = addressLen-zipLen;
      //            sb = new StringBuilder();
      //            while (true) {
      //                sb.append(" ");
      //                if (baseFont.getWidthPoint(sb.toString(), 12.0f)>=padlen) {
      //                    break;
      //                }
      //            }
      //            String space = sb.toString();
      StringBuilder sb = new StringBuilder();
      sb.append(zipCode);
      cell = createNoBorderCell(sb.toString());
      cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      pTable.addCell(cell);

      sb = new StringBuilder();
      sb.append(address);
      cell = createNoBorderCell(sb.toString());
      cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      pTable.addCell(cell);

      // 病院名
      cell = createNoBorderCell(model.getConsultantHospital());
      cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      pTable.addCell(cell);

      // 電話番号
      cell = createNoBorderCell(model.getConsultantTelephone());
      cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      pTable.addCell(cell);

      // 医師
      sb = new StringBuilder();
      sb.append("医 師 ").append(model.getConsultantDoctor()).append(" 印");
      cell = createNoBorderCell(sb.toString());
      cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
      pTable.addCell(cell);
      document.add(pTable);

      document.close();

      // // pdf content bytes
      byte[] pdfbytes = byteo.toByteArray();

      // 評価でない場合は Fileへ書き込んでリターン
      if (!ClientContext.is5mTest()) {
        // minagawa^
        //                FileOutputStream fout = new FileOutputStream(pathToPDF);
        //                FileChannel channel = fout.getChannel();
        //                ByteBuffer bytebuff = ByteBuffer.wrap(pdfbytes);
        //
        //                while(bytebuff.hasRemaining()) {
        //                    channel.write(bytebuff);
        //                }
        //                channel.close();
        Files.write(pathObj, pdfbytes);
        // minagawa$
        return getPathToPDF();
      }

      // 評価の場合は water Mark を書く
      PdfReader pdfReader = new PdfReader(pdfbytes);
      // minagawa~
      //            PdfStamper pdfStamper = new PdfStamper(pdfReader,new
      // FileOutputStream(pathToPDF));
      PdfStamper pdfStamper = new PdfStamper(pdfReader, Files.newOutputStream(pathObj));
      // minagawa$
      Image image = Image.getInstance(ClientContext.getImageResource("water-mark.png"));

      for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {

        PdfContentByte content = pdfStamper.getUnderContent(i);
        image.scaleAbsolute(PageSize.A4.getWidth(), PageSize.A4.getHeight());
        image.setAbsolutePosition(0.0f, 0.0f);

        content.addImage(image);
      }

      pdfStamper.close();

      return getPathToPDF();

    } catch (IOException ex) {
      ClientContext.getBootLogger().warn(ex);
      throw new RuntimeException(ERROR_IO);
    } catch (DocumentException ex) {
      ClientContext.getBootLogger().warn(ex);
      throw new RuntimeException(ERROR_PDF);
    }
  }
    public ByteArrayOutputStream getFilledPdf(Person person) throws IOException, DocumentException {
      InputStream istream = getClass().getResourceAsStream(SANTANDER_APPLICATION_PDF_PATH);
      PdfReader reader = new PdfReader(istream);
      reader.getAcroForm().remove(PdfName.SIGFLAGS);
      reader.selectPages("1,2");
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      PdfStamper stamper = new PdfStamper(reader, output);
      form = stamper.getAcroFields();

      setField("topmostSubform[0].Page1[0].Nomecompleto[0]", person.getName());
      String documentIdNumber = person.getDocumentIdNumber();
      if (person.getIdDocumentType().equals(IDDocumentType.CITIZEN_CARD)
          || person.getIdDocumentType().equals(IDDocumentType.IDENTITY_CARD)) {
        setField("topmostSubform[0].Page1[0].NumBICartaoCidadaooutro[0]", documentIdNumber);
        setField(
            "topmostSubform[0].Page1[0].Checkdigit[0]",
            person.getIdentificationDocumentSeriesNumberValue());
      } else {
        setField("topmostSubform[0].Page1[0].Outrotipodocidentificacao[0]", documentIdNumber);
      }

      YearMonthDay emissionDate = person.getEmissionDateOfDocumentIdYearMonthDay();
      if (emissionDate != null) {
        setField(
            "topmostSubform[0].Page1[0].Dataemissao[0]",
            emissionDate.toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
      }
      setField(
          "topmostSubform[0].Page1[0].Datavalidade[0]",
          person
              .getExpirationDateOfDocumentIdYearMonthDay()
              .toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
      setField("topmostSubform[0].Page1[0].NIF[0]", person.getSocialSecurityNumber());
      setField(
          "topmostSubform[0].Page1[0].Nacionalidade[0]",
          person.getCountryOfBirth().getCountryNationality().toString());
      setField(
          "topmostSubform[0].Page1[0].Datanascimento[0]",
          person.getDateOfBirthYearMonthDay().toString(DateTimeFormat.forPattern("dd/MM/yyyy")));
      YearMonthDay dateOfBirthYearMonthDay = person.getDateOfBirthYearMonthDay();
      Period periodBetween = new Period(dateOfBirthYearMonthDay, new YearMonthDay());
      setField(
          "topmostSubform[0].Page1[0].Idadeactual[0]",
          String.valueOf(periodBetween.get(DurationFieldType.years())));
      if (person.isFemale()) {
        setField("topmostSubform[0].Page1[0].Sexo[0]", "F"); // female
      } else if (person.isMale()) {
        setField("topmostSubform[0].Page1[0].Sexo[0]", "M"); // male
      }

      switch (person.getMaritalStatus()) {
        case CIVIL_UNION:
          setField("topmostSubform[0].Page1[0].Uniaofacto[0]", "1");
          break;
        case DIVORCED:
          setField("topmostSubform[0].Page1[0].Divorciado[0]", "1");
          break;
        case MARRIED:
          setField("topmostSubform[0].Page1[0].Casado[0]", "1");
          break;
        case SEPARATED:
          setField("topmostSubform[0].Page1[0].Separado[0]", "1");
          break;
        case SINGLE:
          setField("topmostSubform[0].Page1[0].Solteiro[0]", "1");
          break;
        case WIDOWER:
          setField("topmostSubform[0].Page1[0].Viuvo[0]", "1");
          break;
      }
      setField("topmostSubform[0].Page1[0].Telemovel[0]", person.getDefaultMobilePhoneNumber());
      setField("topmostSubform[0].Page1[0].E-mail[0]", getMail(person));
      setField("topmostSubform[0].Page1[0].Moradaprincipal[0]", person.getAddress());
      setField("topmostSubform[0].Page1[0].localidade[0]", person.getAreaOfAreaCode());
      String postalCode = person.getPostalCode();
      int dashIndex = postalCode.indexOf('-');
      setField("topmostSubform[0].Page1[0].CodPostal[0]", postalCode.substring(0, 4));
      String last3Numbers = person.getPostalCode().substring(dashIndex + 1, dashIndex + 4);
      setField("topmostSubform[0].Page1[0].ExtensaoCodPostal[0]", last3Numbers);

      setField(
          "topmostSubform[0].Page1[0].Nacionalidade[0]",
          person.getCountryOfBirth().getCountryNationality().toString());
      setField(
          "topmostSubform[0].Page1[0].Nacionalidade[0]",
          person.getCountryOfBirth().getCountryNationality().toString());

      stamper.setFormFlattening(true);
      stamper.close();
      return output;
    }
  /**
   * Process the specified HTTP request, and create the corresponding HTTP response (or forward to
   * another web component that will create it). Return an <code>ActionForward</code> instance
   * describing where and how control should be forwarded, or <code>null</code> if the response has
   * already been completed.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @exception Exception if business logic throws an exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // Extract attributes we will need
    MessageResources messages = getResources(request);

    // save errors
    ActionMessages errors = new ActionMessages();

    // START check for login (security)
    if (!SecurityService.getInstance().checkForLogin(request.getSession(false))) {
      return (mapping.findForward("welcome"));
    }
    // END check for login (security)

    // START get id of current project from either request, attribute, or cookie
    // id of project from request
    String projectId = null;
    projectId = request.getParameter("projectViewId");

    // check attribute in request
    if (projectId == null) {
      projectId = (String) request.getAttribute("projectViewId");
    }

    // id of project from cookie
    if (projectId == null) {
      projectId = StandardCode.getInstance().getCookie("projectViewId", request.getCookies());
    }

    // default project to last if not in request or cookie
    if (projectId == null) {
      java.util.List results = ProjectService.getInstance().getProjectList();

      ListIterator iterScroll = null;
      for (iterScroll = results.listIterator(); iterScroll.hasNext(); iterScroll.next()) {}
      iterScroll.previous();
      Project p = (Project) iterScroll.next();
      projectId = String.valueOf(p.getProjectId());
    }

    Integer id = Integer.valueOf(projectId);

    // END get id of current project from either request, attribute, or cookie

    // get project
    Project p = ProjectService.getInstance().getSingleProject(id);

    // get user (project manager)
    User u =
        UserService.getInstance()
            .getSingleUserRealName(
                StandardCode.getInstance().getFirstName(p.getPm()),
                StandardCode.getInstance().getLastName(p.getPm()));

    // START process pdf
    try {
      PdfReader reader = new PdfReader("C://templates/CL01_001.pdf"); // the template

      // save the pdf in memory
      ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();

      // the filled-in pdf
      PdfStamper stamp = new PdfStamper(reader, pdfStream);

      // stamp.setEncryption(true, "pass", "pass", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);
      AcroFields form1 = stamp.getAcroFields();
      Date cDate = new Date();
      Integer month = cDate.getMonth();
      Integer day = cDate.getDate();
      Integer year = cDate.getYear() + 1900;
      String[] monthName = {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
      };

      // set the field values in the pdf form
      // form1.setField("", projectId)
      form1.setField("currentdate", monthName[month] + " " + day + ", " + year);
      form1.setField(
          "firstname", StandardCode.getInstance().noNull(p.getContact().getFirst_name()));
      form1.setField("pm", p.getPm());
      form1.setField("emailpm", u.getWorkEmail1());
      if (u.getWorkPhoneEx() != null && u.getWorkPhoneEx().length() > 0) { // ext present
        form1.setField(
            "phonepm",
            StandardCode.getInstance().noNull(u.getWorkPhone())
                + " ext "
                + StandardCode.getInstance().noNull(u.getWorkPhoneEx()));
      } else { // no ext present
        form1.setField("phonepm", StandardCode.getInstance().noNull(u.getWorkPhone()));
      }
      form1.setField("faxpm", StandardCode.getInstance().noNull(u.getLocation().getFax_number()));
      form1.setField("postalpm", StandardCode.getInstance().printLocation(u.getLocation()));

      // START add images
      //                if(u.getPicture() != null && u.getPicture().length() > 0) {
      //                    PdfContentByte over;
      //                    Image img = Image.getInstance("C:/Program Files (x86)/Apache Software
      // Foundation/Tomcat 7.0/webapps/logo/images/" + u.getPicture());
      //                    img.setAbsolutePosition(200, 200);
      //                    over = stamp.getOverContent(1);
      //                    over.addImage(img, 54, 0,0, 65, 47, 493);
      //                }
      // END add images
      form1.setField("productname", StandardCode.getInstance().noNull(p.getProduct()));
      form1.setField("project", p.getNumber() + p.getCompany().getCompany_code());
      form1.setField("description", StandardCode.getInstance().noNull(p.getProductDescription()));
      form1.setField("additional", p.getProjectRequirements());

      // get sources and targets
      StringBuffer sources = new StringBuffer("");
      StringBuffer targets = new StringBuffer("");
      if (p.getSourceDocs() != null) {
        for (Iterator iterSource = p.getSourceDocs().iterator(); iterSource.hasNext(); ) {
          SourceDoc sd = (SourceDoc) iterSource.next();
          sources.append(sd.getLanguage() + " ");
          if (sd.getTargetDocs() != null) {
            for (Iterator iterTarget = sd.getTargetDocs().iterator(); iterTarget.hasNext(); ) {
              TargetDoc td = (TargetDoc) iterTarget.next();
              if (!td.getLanguage().equals("All")) targets.append(td.getLanguage() + " ");
            }
          }
        }
      }

      form1.setField("source", sources.toString());
      form1.setField("target", targets.toString());
      form1.setField(
          "start",
          (p.getStartDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getStartDate())
              : "");
      form1.setField(
          "due",
          (p.getDueDate() != null)
              ? DateFormat.getDateInstance(DateFormat.SHORT).format(p.getDueDate())
              : "");

      if (p.getCompany().getCcurrency().equalsIgnoreCase("USD")) {

        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "$ " + StandardCode.getInstance().formatDouble(p.getProjectAmount())
                : "");
      } else {
        form1.setField(
            "cost",
            (p.getProjectAmount() != null)
                ? "€ "
                    + StandardCode.getInstance()
                        .formatDouble(p.getProjectAmount() / p.getEuroToUsdExchangeRate())
                : "");
      }
      // stamp.setFormFlattening(true);
      stamp.close();

      // write to client (web browser)

      response.setHeader(
          "Content-disposition",
          "attachment; filename="
              + p.getNumber()
              + p.getCompany().getCompany_code()
              + "-Order-Confirmation"
              + ".pdf");

      OutputStream os = response.getOutputStream();
      pdfStream.writeTo(os);
      os.flush();
    } catch (Exception e) {
      System.err.println("PDF Exception:" + e.getMessage());
      throw new RuntimeException(e);
    }
    // END process pdf

    // Forward control to the specified success URI
    return (mapping.findForward("Success"));
  }