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;
 }
 /* (non-Javadoc)
  * @see de.offis.health.icardea.cied.pdf.interfaces.PDFExtractor#getNumberOfPages()
  */
 public int getNumberOfPages() {
   int numberOfPages = -1;
   if (pdfReader != null) {
     numberOfPages = pdfReader.getNumberOfPages();
   }
   return numberOfPages;
 }
 public List<PdfDocumentDescriptor> load(List<PdfDocumentDescriptor> toLoad) {
   LOG.debug(DefaultI18nContext.getInstance().i18n("Loading documents"));
   List<PdfDocumentDescriptor> loaded = new ArrayList<>(toLoad.size());
   for (PdfDocumentDescriptor current : toLoad) {
     PdfDocumentDescriptor copy = newCopy(current);
     PdfReader reader = null;
     try {
       reader = current.toPdfSource().open(PdfSourceOpeners.newPartialReadOpener());
       copy.setEncryptionStatus(EncryptionStatus.NOT_ENCRYPTED);
       copy.setPages(reader.getNumberOfPages());
       copy.setVersion(String.format("1.%c", reader.getPdfVersion()));
       @SuppressWarnings("unchecked")
       Map<String, String> meta = reader.getInfo();
       for (PdfMetadataKey key : PdfMetadataKey.values()) {
         copy.addMedatada(key, defaultString(meta.get(key.getKey())));
       }
       loaded.add(copy);
     } catch (TaskWrongPasswordException twpe) {
       copy.setEncryptionStatus(EncryptionStatus.ENCRYPTED);
       loaded.add(copy);
       LOG.warn(String.format("Owner password required %s", current.getFileName()), twpe);
     } catch (Exception e) {
       LOG.error(
           String.format("An error occured loading the document %s", current.getFileName()), e);
     } finally {
       nullSafeClosePdfReader(reader);
     }
   }
   LOG.debug(DefaultI18nContext.getInstance().i18n("Documents loaded"));
   return loaded;
 }
  /* (non-Javadoc)
   * @see de.offis.health.icardea.cied.pdf.interfaces.PDFExtractor#openDocument()
   */
  public boolean openDocument(String fullPDFFilePath) throws IOException, Exception {
    boolean returnCode = false;

    if (fullPDFFilePath == null) {
      throw new Exception("There is no full path to a file given.");
    } // end if

    File pdfFile = new File(fullPDFFilePath);
    if (pdfFile.isFile() && pdfFile.canRead()) {
      this.fullPDFFilePath = pdfFile.getAbsolutePath();
      this.fullPDFDirectoryPath = pdfFile.getPath();

      logger.debug("FilePath.....: " + this.fullPDFFilePath);
      logger.debug("DirectoryPath: " + this.fullPDFDirectoryPath);

      // Open the PDF file
      pdfReader = new PdfReader(pdfFile.getAbsolutePath());

      logger.debug("PDF contains pages: " + pdfReader.getNumberOfPages());

      // Remove reference to the file object as it is no longer needed (cleanup)
      pdfFile = null;

      returnCode = true;
    } else {
      throw new Exception("The given PDF file is not a file or not readable (check permissions).");
    } // end if..else
    return returnCode;
  }
Exemple #5
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));
        }
      }
    }
  }
Exemple #6
0
 /** RowContainer */
 RowContainer(File file) {
   this.file = file;
   PdfReader reader = null;
   try {
     reader = new PdfReader(file.getAbsolutePath());
   } catch (IOException ex) {
   }
   this.pages = reader.getNumberOfPages();
 }
 public void addDocument(PdfReader reader) throws Exception {
   if (reader != null) {
     int numPages = reader.getNumberOfPages();
     for (int count = 1; count <= numPages; count++) {
       writer.addPage(writer.getImportedPage(reader, count));
     }
   } else {
     throw new DocumentException("Reader is null");
   }
 }
Exemple #8
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();
  }
  /**
   * This method will write the text extracted from the PDF document into a file with the extension
   * <code>.txt</code>.
   *
   * @param fullExportDirectoryPath The optional full export path where the text file should be
   *     stored. If not given, the location of the original PDF file is used.
   * @throws Exception
   */
  private void textExtractor(String fullExportDirectoryPath) throws Exception {
    if (fullExportDirectoryPath != null) {
      fullExportDirectoryPath = GlobalTools.checkDirectoryPath(fullExportDirectoryPath);
      File exportDirectory = new File(fullExportDirectoryPath);
      if (!exportDirectory.exists()) {
        exportDirectory.mkdirs();
      } // end if
    } // end if

    String baseExportDirectoryPath =
        fullExportDirectoryPath != null ? fullExportDirectoryPath : this.fullPDFDirectoryPath;
    String baseFileNameWithoutExtension =
        GlobalTools.getFileNameWithoutExtension(this.fullPDFFilePath);

    // Writer object to write files
    Writer out = null;
    StringBuffer stringBuffer = new StringBuffer();
    String pageText = null;

    int numberOfPages = pdfReader.getNumberOfPages();
    for (int currentPage = 1; currentPage <= numberOfPages; currentPage++) {
      pageText = getText(currentPage);
      if (pageText != null) {
        stringBuffer.append(pageText);
      } else {
        logger.debug("The call of getText(" + currentPage + ") returned: null");
      } // end if..else
    } // end for

    // If we have something to write, open a file to write the content.
    String fullExportFileNameWithExtension =
        baseExportDirectoryPath + baseFileNameWithoutExtension + ".txt";
    if (stringBuffer.length() > 0) {
      logger.debug(
          "Full export filename with extension: '" + fullExportFileNameWithExtension + "'");
      out =
          new BufferedWriter(
              new OutputStreamWriter(
                  new FileOutputStream(fullExportFileNameWithExtension), "UTF8"));
      out.write(stringBuffer.toString());
      out.flush();
      out.close();
    } else {
      logger.debug(
          "Nothing to export to file '"
              + GlobalTools.getFileNameWithoutFullPath(fullExportFileNameWithExtension)
              + "'");
    } // end if..else
  }
  public String rubricarTodas(IVFile pdffile) {
    int pageCount = 0;
    try {

      String read = saveToFile(pdffile);
      PdfReader reader = new PdfReader(read);
      pageCount = reader.getNumberOfPages();
      String write = saveToFile(pdffile);
      insertImageRubrica(reader, pageCount, write);
      deleteFile(read);
      return write;

    } catch (IOException e) {
      e.printStackTrace();
      return "";
    }
  }
 public void manipulatePdf(String src, String dest, int pow)
     throws IOException, DocumentException {
   PdfReader reader = new PdfReader(src);
   Rectangle pageSize = reader.getPageSize(1);
   Rectangle newSize =
       (pow % 2) == 0
           ? new Rectangle(pageSize.getWidth(), pageSize.getHeight())
           : new Rectangle(pageSize.getHeight(), pageSize.getWidth());
   Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight());
   for (int i = 0; i < pow; i++) {
     unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth());
   }
   int n = (int) Math.pow(2, pow);
   int r = (int) Math.pow(2, pow / 2);
   int c = n / r;
   Document document = new Document(newSize, 0, 0, 0, 0);
   PdfWriter writer =
       PdfWriter.getInstance(document, new FileOutputStream(String.format(dest, n)));
   document.open();
   PdfContentByte cb = writer.getDirectContent();
   PdfImportedPage page;
   Rectangle currentSize;
   float offsetX, offsetY, factor;
   int total = reader.getNumberOfPages();
   for (int i = 0; i < total; ) {
     if (i % n == 0) {
       document.newPage();
     }
     currentSize = reader.getPageSize(++i);
     factor =
         Math.min(
             unitSize.getWidth() / currentSize.getWidth(),
             unitSize.getHeight() / currentSize.getHeight());
     offsetX =
         unitSize.getWidth() * ((i % n) % c)
             + (unitSize.getWidth() - (currentSize.getWidth() * factor)) / 2f;
     offsetY =
         newSize.getHeight()
             - (unitSize.getHeight() * (((i % n) / c) + 1))
             + (unitSize.getHeight() - (currentSize.getHeight() * factor)) / 2f;
     page = writer.getImportedPage(reader, i);
     cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
   }
   document.close();
 }
  /**
   * Reads a PDF file for retrieving its metadata.
   *
   * @param file File
   */
  public void createTextFromPDF(File file) {
    if (file.exists()) {
      int page = 1;
      PdfReader reader = null;

      try {
        reader = new PdfReader(new RandomAccessFileOrArray(file.getAbsolutePath()), null);
        HashMap<String, String> pdfinfo = reader.getInfo();

        StringBuffer sb = new StringBuffer();
        sb.append("<html>=== Document Information ===<p>");
        sb.append(
            reader.getCropBox(page).getHeight() + "*" + reader.getCropBox(page).getWidth() + "<p>");
        sb.append("PDF Version: " + reader.getPdfVersion() + "<p>");
        sb.append("Number of pages: " + reader.getNumberOfPages() + "<p>");
        sb.append("Number of PDF objects: " + reader.getXrefSize() + "<p>");
        sb.append("File length: " + reader.getFileLength() + "<p>");
        sb.append("Encrypted= " + reader.isEncrypted() + "<p>");
        if (pdfinfo.get("Title") != null) {
          sb.append("Title= " + pdfinfo.get("Title") + "<p>");
        }
        if (pdfinfo.get("Author") != null) {
          sb.append("Author= " + pdfinfo.get("Author") + "<p>");
        }
        if (pdfinfo.get("Subject") != null) {
          sb.append("Subject= " + pdfinfo.get("Subject") + "<p>");
        }
        if (pdfinfo.get("Producer") != null) {
          sb.append("Producer= " + pdfinfo.get("Producer") + "<p>");
        }
        if (pdfinfo.get("ModDate") != null) {
          sb.append("ModDate= " + PdfDate.decode(pdfinfo.get("ModDate")).getTime() + "<p>");
        }
        if (pdfinfo.get("CreationDate") != null) {
          sb.append(
              "CreationDate= " + PdfDate.decode(pdfinfo.get("CreationDate")).getTime() + "<p>");
        }
        sb.append("</html>");
        label.setText(sb.toString());
      } catch (IOException ex) {
        label.setText("");
      }
    }
  }
  /** @see com.lowagie.toolbox.AbstractTool#execute() */
  public void execute() {
    try {
      if (getValue("srcfile") == null)
        throw new InstantiationException("You need to choose a sourcefile");
      File src = (File) getValue("srcfile");

      // we create a reader for a certain document
      PdfReader reader = new PdfReader(src.getAbsolutePath());
      final File parentFile = src.getParentFile();
      final String outPath;
      if (parentFile != null) {
        outPath = parentFile.getAbsolutePath();
      } else {
        outPath = "";
      }
      PdfDictionary catalog = reader.getCatalog();
      PdfDictionary names = catalog.getAsDict(PdfName.NAMES);
      if (names != null) {
        PdfDictionary embFiles = names.getAsDict(new PdfName("EmbeddedFiles"));
        if (embFiles != null) {
          HashMap<String, PdfObject> embMap = PdfNameTree.readTree(embFiles);
          for (Iterator<PdfObject> i = embMap.values().iterator(); i.hasNext(); ) {
            PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(i.next());
            unpackFile(reader, filespec, outPath);
          }
        }
      }
      for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
        PdfArray annots = reader.getPageN(k).getAsArray(PdfName.ANNOTS);
        if (annots == null) continue;
        for (Iterator<PdfObject> i = annots.listIterator(); i.hasNext(); ) {
          PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(i.next());
          PdfName subType = annot.getAsName(PdfName.SUBTYPE);
          if (!PdfName.FILEATTACHMENT.equals(subType)) continue;
          PdfDictionary filespec = annot.getAsDict(PdfName.FS);
          unpackFile(reader, filespec, outPath);
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /** extracts attachments from PDF File */
  @SuppressWarnings("unchecked")
  protected Map extractAttachments(PdfReader reader) throws IOException {
    Map fileMap = new HashMap();
    PdfDictionary catalog = reader.getCatalog();
    PdfDictionary names = (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.NAMES));
    if (names != null) {
      PdfDictionary embFiles =
          (PdfDictionary) PdfReader.getPdfObject(names.get(new PdfName("EmbeddedFiles")));
      if (embFiles != null) {
        HashMap embMap = PdfNameTree.readTree(embFiles);
        for (Iterator i = embMap.values().iterator(); i.hasNext(); ) {
          PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject((PdfObject) i.next());
          Object fileInfo[] = unpackFile(reader, filespec);
          if (fileMap.containsKey(fileInfo[0])) {
            throw new RuntimeException(DUPLICATE_FILE_NAMES);
          }
          fileMap.put(fileInfo[0], fileInfo[1]);
        }
      }
    }
    for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
      PdfArray annots = (PdfArray) PdfReader.getPdfObject(reader.getPageN(k).get(PdfName.ANNOTS));
      if (annots == null) {
        continue;
      }
      for (Iterator i = annots.getArrayList().listIterator(); i.hasNext(); ) {
        PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject((PdfObject) i.next());
        PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE));
        if (!PdfName.FILEATTACHMENT.equals(subType)) {
          continue;
        }
        PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(annot.get(PdfName.FS));
        Object fileInfo[] = unpackFile(reader, filespec);
        if (fileMap.containsKey(fileInfo[0])) {
          throw new RuntimeException(DUPLICATE_FILE_NAMES);
        }

        fileMap.put(fileInfo[0], fileInfo[1]);
      }
    }

    return fileMap;
  }
Exemple #15
0
 @SuppressWarnings("unchecked")
 public static byte[] extractAttachmentFiles(PdfReader reader, String suffix) throws IOException {
   PdfDictionary catalog = reader.getCatalog();
   PdfDictionary names = (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.NAMES));
   if (names != null) {
     PdfDictionary embFiles =
         (PdfDictionary) PdfReader.getPdfObject(names.get(new PdfName("EmbeddedFiles")));
     if (embFiles != null) {
       HashMap<?, PdfObject> embMap = PdfNameTree.readTree(embFiles);
       for (Iterator<PdfObject> i = embMap.values().iterator(); i.hasNext(); ) {
         PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(i.next());
         byte[] ret = unpackFile(reader, filespec, suffix);
         if (ret != null) {
           return ret;
         }
       }
     }
   }
   for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
     PdfArray annots = (PdfArray) PdfReader.getPdfObject(reader.getPageN(k).get(PdfName.ANNOTS));
     if (annots == null) {
       continue;
     }
     for (Iterator<PdfObject> i = annots.listIterator(); i.hasNext(); ) {
       PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(i.next());
       PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE));
       if (!PdfName.FILEATTACHMENT.equals(subType)) {
         continue;
       }
       PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(annot.get(PdfName.FS));
       byte[] ret = unpackFile(reader, filespec, suffix);
       if (ret != null) {
         return ret;
       }
     }
   }
   return null;
 }
Exemple #16
0
 private void renderPDF(OutputStream out, Request request, Response response) throws Exception {
   Map<?, ?> properties = Play.configuration;
   String uri = request.getBase() + request.url;
   if (docs.documents.size() == 1) {
     renderDoc(docs.documents.get(0), uri, properties, out);
   } else {
     // we need to concatenate them all
     Document resultDocument = new Document();
     PdfCopy copy = new PdfCopy(resultDocument, out);
     resultDocument.open();
     ByteArrayOutputStream os = new ByteArrayOutputStream();
     for (PDFDocument doc : docs.documents) {
       os.reset();
       renderDoc(doc, uri, properties, os);
       PdfReader pdfReader = new PdfReader(os.toByteArray());
       int n = pdfReader.getNumberOfPages();
       for (int i = 0; i < n; i++) {
         copy.addPage(copy.getImportedPage(pdfReader, i + 1));
       }
       copy.freeReader(pdfReader);
     }
     resultDocument.close();
   }
 }
Exemple #17
0
 public void addBlankPageIfOdd(PdfReader reader) {
   if (reader.getNumberOfPages() % 2 != 0) {
     addBlankPage(reader);
   }
 }
Exemple #18
0
 /**
  * Adds to the {@link PdfSmartCopy} all the pages from the input reader
  *
  * @param reader
  * @throws TaskException
  */
 public void addAllPages(PdfReader reader) throws TaskException {
   for (int i = 1; i <= reader.getNumberOfPages(); i++) {
     addPage(reader, i);
   }
 }
Exemple #19
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));
        }
      }
    }
  }
Exemple #20
0
  public static void concatPDFs(
      List<InputStream> streamOfPDFFiles,
      InputStream fs,
      OutputStream outputStream,
      boolean paginate)
      throws IOException {

    Document document = new Document(new PdfReader(fs).getPageSize(1));
    try {
      List<InputStream> pdfs = streamOfPDFFiles;
      List<PdfReader> readers = new ArrayList<PdfReader>();
      int totalPages = 0;
      Iterator<InputStream> iteratorPDFs = pdfs.iterator();

      // Create Readers for the pdfs.
      while (iteratorPDFs.hasNext()) {
        InputStream pdf = iteratorPDFs.next();
        PdfReader pdfReader = new PdfReader(pdf);
        readers.add(pdfReader);
        totalPages += pdfReader.getNumberOfPages();
      }
      // Create a writer for the outputstream
      PdfWriter writer = PdfWriter.getInstance(document, outputStream);

      document.open();
      BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
      PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
      // data

      PdfImportedPage page;
      int currentPageNumber = 0;
      int pageOfCurrentReaderPDF = 0;
      Iterator<PdfReader> iteratorPDFReader = readers.iterator();

      // Loop through the PDF files and add to the output.
      while (iteratorPDFReader.hasNext()) {
        PdfReader pdfReader = iteratorPDFReader.next();

        // Create a new page in the target for each source page.
        while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
          document.newPage();
          pageOfCurrentReaderPDF++;
          currentPageNumber++;
          page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
          cb.addTemplate(page, 0, 0);

          // Code for pagination.
          if (paginate) {
            cb.beginText();
            cb.setFontAndSize(bf, 9);
            cb.showTextAligned(
                PdfContentByte.ALIGN_CENTER,
                "" + currentPageNumber + " of " + totalPages,
                520,
                5,
                0);
            cb.endText();
          }
        }
        pageOfCurrentReaderPDF = 0;
      }
      outputStream.flush();
      document.close();
      outputStream.close();
    } catch (Exception e) {
      log.error(e.getLocalizedMessage(), e);
    } finally {
      if (document.isOpen()) document.close();
      try {
        if (outputStream != null) outputStream.close();
      } catch (IOException ioe) {
        log.error(ioe.getLocalizedMessage(), ioe);
      }
    }
  }
  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;
  }
Exemple #22
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";
  }
  @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);
    }
  }