/* (non-Javadoc)
   * @see de.offis.health.icardea.cied.pdf.interfaces.PDFExtractor#getBookmarkContentAsText()
   */
  @SuppressWarnings("unchecked")
  public java.util.List getBookmarkTitlesAsText() {
    java.util.List bookmarkContent = null;
    if (pdfReader != null) {
      // bookmarkContent = SimpleBookmark.getBookmark(pdfReader);

      PdfDictionary catalog = pdfReader.getCatalog();
      if (catalog != null) {
        PdfObject rootPdfObject = PdfReader.getPdfObjectRelease(catalog.get(PdfName.OUTLINES));
        if (rootPdfObject != null && rootPdfObject.isDictionary()) {
          PdfDictionary rootOutlinesPdfDictionary = (PdfDictionary) rootPdfObject;
          /*
           * If it doesn't exist create the List and populate it,
           * otherwise just return the already existing List.
           */
          if (bookmarkTextList == null) {
            bookmarkTextList = new ArrayList<String>();

            // Populate the List
            populateBookmarkTextList(rootOutlinesPdfDictionary, "");
          } // end if
        }
      } // end if
    }
    return bookmarkContent;
  }
  /**
   * Unpacks a file attachment.
   *
   * @param reader The object that reads the PDF document
   * @param filespec The dictonary containing the file specifications
   * @throws IOException
   */
  protected static Object[] unpackFile(PdfReader reader, PdfDictionary filespec)
      throws IOException {
    Object arr[] = new Object[2]; // use to store name and file bytes
    if (filespec == null) {
      return null;
    }

    PdfName type = (PdfName) PdfReader.getPdfObject(filespec.get(PdfName.TYPE));
    if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type)) {
      return null;
    }

    PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(filespec.get(PdfName.EF));
    if (ef == null) {
      return null;
    }

    PdfString fn = (PdfString) PdfReader.getPdfObject(filespec.get(PdfName.F));
    if (fn == null) {
      return null;
    }

    File fLast = new File(fn.toUnicodeString());
    PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
    if (prs == null) {
      return null;
    }

    byte attachmentByte[] = PdfReader.getStreamBytes(prs);
    arr[0] = fLast.getName();
    arr[1] = attachmentByte;

    return arr;
  }
Exemple #3
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;
 }
    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;
    }
  /**
   * Unpacks a file attachment.
   *
   * @param reader The object that reads the PDF document
   * @param filespec The dictionary containing the file specifications
   * @param outPath The path where the attachment has to be written
   * @throws IOException
   */
  private static byte[] unpackFile(PdfReader reader, PdfDictionary filespec, String suffix)
      throws IOException {
    if (filespec == null) {
      return null;
    }
    PdfName type = (PdfName) PdfReader.getPdfObject(filespec.get(PdfName.TYPE));
    if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type)) {
      return null;
    }
    PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(filespec.get(PdfName.EF));
    if (ef == null) {
      return null;
    }
    PdfString fn = (PdfString) PdfReader.getPdfObject(filespec.get(PdfName.F));
    if (fn == null) {
      return null;
    }
    File fLast = new File(fn.toUnicodeString());
    String filename = fLast.getName();

    if (!filename.endsWith(suffix)) {
      return null;
    }

    PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
    if (prs == null) {
      return null;
    }
    return PdfReader.getStreamBytes(prs);
  }
 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;
 }
Exemple #7
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 #8
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;
 }
Exemple #10
0
 /** RowContainer */
 RowContainer(File file) {
   this.file = file;
   PdfReader reader = null;
   try {
     reader = new PdfReader(file.getAbsolutePath());
   } catch (IOException ex) {
   }
   this.pages = reader.getNumberOfPages();
 }
 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 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;
    }
Exemple #13
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();
  }
  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();
    }
  }
    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;
    }
Exemple #16
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);
  }
Exemple #17
0
 /**
  * Opens the copier using the given reader and the given output version.
  *
  * @param reader
  * @param outputStream the output stream to write to.
  * @param version version for the created pdf copy, if null the version number is taken from the
  *     input {@link PdfReader}
  */
 void open(PdfReader reader, OutputStream outputStream, PdfVersion version) throws TaskException {
   try {
     pdfDocument = new Document(reader.getPageSizeWithRotation(1));
     pdfCopy = new PdfSmartCopy(pdfDocument, outputStream);
     if (version == null) {
       pdfCopy.setPdfVersion(reader.getPdfVersion());
     } else {
       pdfCopy.setPdfVersion(version.getVersionAsCharacter());
     }
     pdfDocument.addCreator(Sejda.CREATOR);
     pdfDocument.open();
   } catch (DocumentException e) {
     throw new TaskException("An error occurred opening the PdfSmartCopy.", e);
   }
 }
  /* (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;
  }
 /* (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;
 }
  /**
   * 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 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 addDocument(PdfReader reader, String ranges) throws Exception {
   if (reader != null) {
     reader.selectPages(ranges);
     addDocument(reader);
   } else {
     throw new DocumentException("Reader is null");
   }
 }
 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();
 }
 /**
  * Loads an object based on its reference number in the xref table.
  *
  * @param ref a reference number in the xref table.
  * @return a PDF object
  */
 public PdfObject loadObjectByReference(int ref) {
   PdfObject object = getObjectByReference(ref);
   if (object instanceof PdfNull) {
     int idx = getIndexByRef(ref);
     object = reader.getPdfObject(ref);
     objects.set(idx, object);
   }
   return object;
 }
  /** 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;
  }
 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");
   }
 }
 public ImageResource getImageResource(String uri) {
   ImageResource resource = null;
   uri = resolveURI(uri);
   resource = (ImageResource) _imageCache.get(uri);
   if (resource == null) {
     InputStream is = resolveAndOpenStream(uri);
     if (is != null) {
       try {
         URL url = new URL(uri);
         if (url.getPath() != null && url.getPath().toLowerCase().endsWith(".pdf")) {
           PdfReader reader = _outputDevice.getReader(url);
           PDFAsImage image = new PDFAsImage(url);
           Rectangle rect = reader.getPageSizeWithRotation(1);
           image.setInitialWidth(rect.getWidth() * _outputDevice.getDotsPerPoint());
           image.setInitialHeight(rect.getHeight() * _outputDevice.getDotsPerPoint());
           resource = new ImageResource(uri, image);
         } else {
           Image image = Image.getInstance(url);
           scaleToOutputResolution(image);
           resource = new ImageResource(uri, new ITextFSImage(image));
         }
         _imageCache.put(uri, resource);
       } catch (IOException e) {
         XRLog.exception("Can't read image file; unexpected problem for URI '" + uri + "'", e);
       } catch (BadElementException e) {
         XRLog.exception("Can't read image file; unexpected problem for URI '" + uri + "'", e);
       } catch (URISyntaxException e) {
         XRLog.exception("Can't read image file; unexpected problem for URI '" + uri + "'", e);
       } finally {
         try {
           is.close();
         } catch (IOException e) {
           // ignore
         }
       }
     }
   }
   if (resource == null) {
     resource = new ImageResource(uri, null);
   }
   return resource;
 }
Exemple #28
0
 /** @see com.lowagie.toolbox.AbstractTool#execute() */
 public void execute() {
   try {
     if (getValue("xmlfile") == null)
       throw new InstantiationException("You need to choose an xml file");
     if (getValue("pdffile") == null)
       throw new InstantiationException("You need to choose a source PDF file");
     PdfReader reader = new PdfReader(((File) getValue("pdffile")).getAbsolutePath());
     reader.consolidateNamedDestinations();
     List<HashMap<String, Object>> bookmarks = SimpleBookmark.getBookmark(reader);
     // save them in XML format
     FileOutputStream bmWriter = new FileOutputStream((File) getValue("xmlfile"));
     SimpleBookmark.exportToXML(bookmarks, bmWriter, "UTF-8", false);
     bmWriter.close();
   } catch (Exception e) {
     e.printStackTrace();
     JOptionPane.showMessageDialog(
         internalFrame, e.getMessage(), e.getClass().getName(), JOptionPane.ERROR_MESSAGE);
     System.err.println(e.getMessage());
   }
 }
 /**
  * Unpacks a file attachment.
  *
  * @param reader The object that reads the PDF document
  * @param filespec The dictionary containing the file specifications
  * @param outPath The path where the attachment has to be written
  * @throws IOException
  */
 public static void unpackFile(PdfReader reader, PdfDictionary filespec, String outPath)
     throws IOException {
   if (filespec == null) return;
   PdfName type = filespec.getAsName(PdfName.TYPE);
   if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type)) return;
   PdfDictionary ef = filespec.getAsDict(PdfName.EF);
   if (ef == null) return;
   PdfString fn = filespec.getAsString(PdfName.F);
   System.out.println("Unpacking file '" + fn + "' to " + outPath);
   if (fn == null) return;
   File fLast = new File(fn.toUnicodeString());
   File fullPath = new File(outPath, fLast.getName());
   if (fullPath.exists()) return;
   PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
   if (prs == null) return;
   byte b[] = PdfReader.getStreamBytes(prs);
   FileOutputStream fout = new FileOutputStream(fullPath);
   fout.write(b);
   fout.close();
 }
  /* (non-Javadoc)
   * @see de.offis.health.icardea.cied.pdf.interfaces.PDFExtractor#getTitle()
   */
  public String getTitle() {
    /*
     * Key = "Title"
     */
    String title = null;
    if (pdfReader != null) {
      Map<?, ?> info = pdfReader.getInfo();
      title = (String) info.get("Title");
    } // end if

    return title;
  }