Exemple #1
0
 /**
  * @param fileToAdd file to add
  * @param password password to open the file
  * @return the item to add to the table
  */
 PdfSelectionTableItem getPdfSelectionTableItem(
     File fileToAdd, String password, String pageSelection) {
   PdfSelectionTableItem tableItem = null;
   PdfReader pdfReader = null;
   if (fileToAdd != null) {
     tableItem = new PdfSelectionTableItem();
     tableItem.setInputFile(fileToAdd);
     tableItem.setPassword(password);
     tableItem.setPageSelection(pageSelection);
     try {
       // fix 03/07 for memory usage
       pdfReader =
           new PdfReader(
               new RandomAccessFileOrArray(new FileInputStream(fileToAdd)),
               (password != null) ? password.getBytes() : null);
       tableItem.setEncrypted(pdfReader.isEncrypted());
       tableItem.setPagesNumber(Integer.toString(pdfReader.getNumberOfPages()));
       tableItem.setPdfVersion(pdfReader.getPdfVersion());
     } catch (Exception e) {
       tableItem.setLoadedWithErrors(true);
       log.error(
           GettextResource.gettext(
                   Configuration.getInstance().getI18nResourceBundle(), "Error loading ")
               + fileToAdd.getAbsolutePath()
               + " :",
           e);
     } finally {
       if (pdfReader != null) {
         pdfReader.close();
         pdfReader = null;
       }
     }
   }
   return tableItem;
 }
Exemple #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();
    }
  }
 public byte[] extractAttachmentFiles(String suffix) throws IOException {
   PdfReader reader = new PdfReader(this.pdfInputStream);
   byte[] bytes = extractAttachmentFiles(reader, suffix);
   reader.close();
   if (bytes == null) {
     return null;
   }
   return bytes;
 }
 protected List<String> getSignatureNames(Blob blob) throws IOException {
   PdfReader reader = new PdfReader(blob.getStream());
   try {
     @SuppressWarnings("unchecked")
     List<String> names = reader.getAcroFields().getSignatureNames();
     return names;
   } finally {
     reader.close();
   }
 }
  public boolean checkDocument(Documents doc) {
    PdfReader reader = null;

    try {
      reader = new PdfReader(doc.getContent());
      return true;
    } catch (Throwable thr) {
      log.warn(thr.getMessage());
      thr.printStackTrace();
      return false;
    } finally {
      if (reader != null) reader.close();
    }
  }
Exemple #6
0
  private void doActionThumbnail() throws PageException, IOException, DocumentException {
    required("pdf", "thumbnail", "source", source);

    PDFDocument doc = toPDFDocument(source, password, null);
    PdfReader pr = doc.getPdfReader();
    boolean isEnc = pr.isEncrypted();
    pr.close();
    if (isEnc) {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      // PDFUtil.concat(new PDFDocument[]{doc}, baos, true, true, true, (char)0);
      PDFUtil.encrypt(doc, baos, null, null, 0, PDFUtil.ENCRYPT_NONE);
      baos.close();
      doc = new PDFDocument(baos.toByteArray(), doc.getResource(), null);
    }

    doc.setPages(pages);

    // scale
    if (scale < 1)
      throw new ApplicationException(
          "value of attribute scale [" + scale + "] should be at least 1");

    // destination
    if (destination == null)
      destination = ResourceUtil.toResourceNotExisting(pageContext, "thumbnails");

    // imagePrefix
    if (imagePrefix == null) {
      Resource res = doc.getResource();
      if (res != null) {
        String n = res.getName();
        int index = n.lastIndexOf('.');
        if (index != -1) imagePrefix = n.substring(0, index);
        else imagePrefix = n;
      } else imagePrefix = "memory";
    }

    // MUST password
    PDFUtil.writeImages(
        doc.getRaw(),
        doc.getPages(),
        destination,
        imagePrefix,
        format,
        scale,
        overwrite,
        resolution == RESOLUTION_HIGH,
        transparent);
  }
  /**
   * 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();
  }
Exemple #8
0
  @Override
  public String parse(String serviceName, String fileName, int fileId, String ipAddr) {

    String providerNo = "-1";
    String filePath = fileName;
    if (!(fileName.endsWith(".pdf") || fileName.endsWith(".PDF"))) {
      logger.error("Document " + fileName + "does not have pdf extension");
      return null;
    } else {
      int fileNameIdx = fileName.lastIndexOf("/");
      fileName = fileName.substring(fileNameIdx + 1);
    }

    EDoc newDoc =
        new EDoc(
            "",
            "",
            fileName,
            "",
            providerNo,
            providerNo,
            "",
            'A',
            oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"),
            "",
            "",
            "demographic",
            "-1",
            false);

    newDoc.setDocPublic("0");

    InputStream fis = null;

    try {
      fis = new FileInputStream(filePath);
      newDoc.setContentType("application/pdf");

      // Find the number of pages
      PdfReader reader = new PdfReader(filePath);
      int numPages = reader.getNumberOfPages();
      reader.close();
      newDoc.setNumberOfPages(numPages);

      String doc_no = EDocUtil.addDocumentSQL(newDoc);

      LogAction.addLog(
          providerNo, LogConst.ADD, LogConst.CON_DOCUMENT, doc_no, ipAddr, "", "DocUpload");

      // Get provider to route document to
      String batchPDFProviderNo =
          OscarProperties.getInstance().getProperty("batch_pdf_provider_no");
      if ((batchPDFProviderNo != null) && !batchPDFProviderNo.isEmpty()) {

        ProviderInboxRoutingDao providerInboxRoutingDao =
            (ProviderInboxRoutingDao) SpringUtils.getBean("providerInboxRoutingDAO");
        providerInboxRoutingDao.addToProviderInbox(
            batchPDFProviderNo, Integer.parseInt(doc_no), "DOC");

        // Add to default queue for now, not sure how or if any other queues can be used anyway
        // (MAB)
        QueueDocumentLinkDao queueDocumentLinkDAO =
            (QueueDocumentLinkDao) SpringUtils.getBean("queueDocumentLinkDAO");
        Integer did = Integer.parseInt(doc_no.trim());
        queueDocumentLinkDAO.addToQueueDocumentLink(1, did);
      }
    } catch (FileNotFoundException e) {
      logger.info("An unexpected error has occurred:" + e.toString());
      return null;
    } catch (Exception e) {
      logger.info("An unexpected error has occurred:" + e.toString());
      return null;
    } finally {
      try {
        if (fis != null) {
          fis.close();
        }
      } catch (IOException e1) {
        logger.info("An unexpected error has occurred:" + e1.toString());
        return null;
      }
    }

    return "success";
  }
  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();
    }
  }