Beispiel #1
0
  /** @see com.lowagie.tools.AbstractTool#execute() */
  public static void execute(String srcvalue, String destvalue, String rotvalue) {
    try {
      if (StringUtils.isBlank(srcvalue)) {
        throw new InstantiationException("You need to choose a sourcefile");
      }
      File src = new File(srcvalue);
      if (StringUtils.isBlank(destvalue)) {
        throw new InstantiationException("You need to choose a destination file");
      }
      File dest = new File(destvalue);
      if (StringUtils.isBlank(rotvalue)) {
        throw new InstantiationException("You need to choose a rotation");
      }
      int rotation = Integer.parseInt(rotvalue);

      // we create a reader for a certain document
      PdfReader reader = new PdfReader(src.getAbsolutePath());
      // we retrieve the total number of pages and the page size
      int total = reader.getNumberOfPages();
      System.out.println("There are " + total + " pages in the original file.");

      PdfDictionary pageDict;
      int currentRotation;
      for (int p = 1; p <= total; p++) {
        currentRotation = reader.getPageRotation(p);
        pageDict = reader.getPageN(p);
        pageDict.put(PdfName.ROTATE, new PdfNumber(currentRotation + rotation));
      }
      PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
      stamper.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #2
0
 public PdfObject getPdfObject(PdfWriter writer) {
   PdfArray array = new PdfArray(PdfName.LAB);
   PdfDictionary dictionary = new PdfDictionary();
   if (whitePoint == null
       || whitePoint.length != 3
       || whitePoint[0] < 0.000001f
       || whitePoint[2] < 0.000001f
       || whitePoint[1] < 0.999999f
       || whitePoint[1] > 1.000001f)
     throw new RuntimeException(MessageLocalization.getComposedMessage("lab.cs.white.point"));
   dictionary.put(PdfName.WHITEPOINT, new PdfArray(whitePoint));
   if (blackPoint != null) {
     if (blackPoint.length != 3
         || blackPoint[0] < -0.000001f
         || blackPoint[1] < -0.000001f
         || blackPoint[2] < -0.000001f)
       throw new RuntimeException(MessageLocalization.getComposedMessage("lab.cs.black.point"));
     dictionary.put(PdfName.BLACKPOINT, new PdfArray(blackPoint));
   }
   if (range != null) {
     if (range.length != 4 || range[0] > range[1] || range[2] > range[3])
       throw new RuntimeException(MessageLocalization.getComposedMessage("lab.cs.range"));
     dictionary.put(PdfName.RANGE, new PdfArray(range));
   }
   array.add(dictionary);
   return array;
 }
 /**
  * Searches for a tag in a page.
  *
  * @param tag the name of the tag
  * @param object an identifier to find the marked content
  * @param page a page dictionary
  * @throws IOException
  */
 public void parseTag(String tag, PdfObject object, PdfDictionary page) throws IOException {
   PRStream stream = (PRStream) page.getAsStream(PdfName.CONTENTS);
   // if the identifier is a number, we can extract the content right away
   if (object instanceof PdfNumber) {
     PdfNumber mcid = (PdfNumber) object;
     RenderFilter filter = new MarkedContentRenderFilter(mcid.intValue());
     TextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
     FilteredTextRenderListener listener = new FilteredTextRenderListener(strategy, filter);
     PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener);
     processor.processContent(PdfReader.getStreamBytes(stream), page.getAsDict(PdfName.RESOURCES));
     out.print(SimpleXMLParser.escapeXML(listener.getResultantText(), true));
   }
   // if the identifier is an array, we call the parseTag method
   // recursively
   else if (object instanceof PdfArray) {
     PdfArray arr = (PdfArray) object;
     int n = arr.size();
     for (int i = 0; i < n; i++) {
       parseTag(tag, arr.getPdfObject(i), page);
       if (i < n - 1) out.println();
     }
   }
   // if the identifier is a dictionary, we get the resources from the
   // dictionary
   else if (object instanceof PdfDictionary) {
     PdfDictionary mcr = (PdfDictionary) object;
     parseTag(tag, mcr.getDirectObject(PdfName.MCID), mcr.getAsDict(PdfName.PG));
   }
 }
Beispiel #4
0
 private void init() {
   encoding = "";
   fontSpecific = false;
   fontType = FONT_TYPE_DOCUMENT;
   PdfName baseFont = font.getAsName(PdfName.BASEFONT);
   fontName = baseFont != null ? PdfName.decodeName(baseFont.toString()) : "Unspecified Font Name";
   PdfName subType = font.getAsName(PdfName.SUBTYPE);
   if (PdfName.TYPE1.equals(subType) || PdfName.TRUETYPE.equals(subType)) doType1TT();
   else {
     PdfName encodingName = font.getAsName(PdfName.ENCODING);
     if (encodingName != null) {
       String enc = PdfName.decodeName(encodingName.toString());
       String ffontname = CJKFont.GetCompatibleFont(enc);
       if (ffontname != null) {
         try {
           cjkMirror = BaseFont.createFont(ffontname, enc, false);
         } catch (Exception e) {
           throw new ExceptionConverter(e);
         }
         cjkEncoding = enc;
         uniMap = ((CJKFont) cjkMirror).getUniMap();
         return;
       }
       if (PdfName.TYPE0.equals(subType) && enc.equals("Identity-H")) {
         processType0(font);
         isType0 = true;
       }
     }
   }
 }
  /**
   * Processes content from the specified page number using the specified listener
   *
   * @param <E> the type of the renderListener - this makes it easy to chain calls
   * @param pageNumber the page number to process
   * @param renderListener the listener that will receive render callbacks
   * @return the provided renderListener
   * @throws IOException if operations on the reader fail
   */
  public <E extends RenderListener> E processContent(int pageNumber, E renderListener)
      throws IOException {
    PdfDictionary pageDic = reader.getPageN(pageNumber);
    PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES);

    PdfContentStreamProcessor processor = new PdfContentStreamProcessor(renderListener);
    processor.processContent(
        ContentByteUtils.getContentBytesForPage(reader, pageNumber), resourcesDic);
    return renderListener;
  }
Beispiel #6
0
 PdfMediaClipData(String file, PdfFileSpecification fs, String mimeType) throws IOException {
   put(PdfName.TYPE, new PdfName("MediaClip"));
   put(PdfName.S, new PdfName("MCD"));
   put(PdfName.N, new PdfString("Media clip for " + file));
   put(new PdfName("CT"), new PdfString(mimeType));
   PdfDictionary dic = new PdfDictionary();
   dic.put(new PdfName("TF"), new PdfString("TEMPACCESS"));
   put(new PdfName("P"), dic);
   put(PdfName.D, fs.getReference());
 }
Beispiel #7
0
  /**
   * Retrieves the page labels from a PDF as an array of String objects.
   *
   * @param reader a PdfReader object that has the page labels you want to retrieve
   * @return a String array or <code>null</code> if no page labels are present
   */
  public static String[] getPageLabels(PdfReader reader) {

    int n = reader.getNumberOfPages();

    PdfDictionary dict = reader.getCatalog();
    PdfDictionary labels =
        (PdfDictionary) PdfReader.getPdfObjectRelease(dict.get(PdfName.PAGELABELS));
    if (labels == null) return null;

    String[] labelstrings = new String[n];

    HashMap<Integer, PdfObject> numberTree = PdfNumberTree.readTree(labels);

    int pagecount = 1;
    Integer current;
    String prefix = "";
    char type = 'D';
    for (int i = 0; i < n; i++) {
      current = Integer.valueOf(i);
      if (numberTree.containsKey(current)) {
        PdfDictionary d = (PdfDictionary) PdfReader.getPdfObjectRelease(numberTree.get(current));
        if (d.contains(PdfName.ST)) {
          pagecount = ((PdfNumber) d.get(PdfName.ST)).intValue();
        } else {
          pagecount = 1;
        }
        if (d.contains(PdfName.P)) {
          prefix = ((PdfString) d.get(PdfName.P)).toUnicodeString();
        }
        if (d.contains(PdfName.S)) {
          type = ((PdfName) d.get(PdfName.S)).toString().charAt(1);
        } else {
          type = 'e';
        }
      }
      switch (type) {
        default:
          labelstrings[i] = prefix + pagecount;
          break;
        case 'R':
          labelstrings[i] = prefix + RomanNumberFactory.getUpperCaseString(pagecount);
          break;
        case 'r':
          labelstrings[i] = prefix + RomanNumberFactory.getLowerCaseString(pagecount);
          break;
        case 'A':
          labelstrings[i] = prefix + RomanAlphabetFactory.getUpperCaseString(pagecount);
          break;
        case 'a':
          labelstrings[i] = prefix + RomanAlphabetFactory.getLowerCaseString(pagecount);
          break;
        case 'e':
          labelstrings[i] = prefix;
          break;
      }
      pagecount++;
    }
    return labelstrings;
  }
Beispiel #8
0
 /**
  * Creates a submit form.
  *
  * @param file the URI to submit the form to
  * @param names the objects to submit
  * @param flags submit properties
  * @return A PdfAction
  */
 public static PdfAction createSubmitForm(String file, Object names[], int flags) {
   PdfAction action = new PdfAction();
   action.put(PdfName.S, PdfName.SUBMITFORM);
   PdfDictionary dic = new PdfDictionary();
   dic.put(PdfName.F, new PdfString(file));
   dic.put(PdfName.FS, PdfName.URL);
   action.put(PdfName.F, dic);
   if (names != null) action.put(PdfName.FIELDS, buildArray(names));
   action.put(PdfName.FLAGS, new PdfNumber(flags));
   return action;
 }
Beispiel #9
0
 /**
  * Adds or replaces a page label.
  *
  * @param page the real page to start the numbering. First page is 1
  * @param numberStyle the numbering style such as LOWERCASE_ROMAN_NUMERALS
  * @param text the text to prefix the number. Can be <CODE>null</CODE> or empty
  * @param firstPage the first logical page number
  */
 public void addPageLabel(int page, int numberStyle, String text, int firstPage) {
   if (page < 1 || firstPage < 1)
     throw new IllegalArgumentException(
         MessageLocalization.getComposedMessage(
             "in.a.page.label.the.page.numbers.must.be.greater.or.equal.to.1"));
   PdfDictionary dic = new PdfDictionary();
   if (numberStyle >= 0 && numberStyle < numberingStyle.length)
     dic.put(PdfName.S, numberingStyle[numberStyle]);
   if (text != null) dic.put(PdfName.P, new PdfString(text, PdfObject.TEXT_UNICODE));
   if (firstPage != 1) dic.put(PdfName.ST, new PdfNumber(firstPage));
   map.put(Integer.valueOf(page - 1), dic);
 }
 /**
  * Parses a string with structured content.
  *
  * @param reader the PdfReader that has access to the PDF file
  * @param os the OutputStream to which the resulting xml will be written
  * @param charset the charset to encode the data
  * @since 5.0.5
  */
 public void convertToXml(PdfReader reader, OutputStream os, String charset) throws IOException {
   this.reader = reader;
   OutputStreamWriter outs = new OutputStreamWriter(os, charset);
   out = new PrintWriter(outs);
   // get the StructTreeRoot from the root object
   PdfDictionary catalog = reader.getCatalog();
   PdfDictionary struct = catalog.getAsDict(PdfName.STRUCTTREEROOT);
   // Inspect the child or children of the StructTreeRoot
   inspectChild(struct.getDirectObject(PdfName.K));
   out.flush();
   out.close();
 }
Beispiel #11
0
 /*
  * the getCatalog method is part of PdfWriter.
  * we wrap this so that we can extend it
  */
 @Override
 protected PdfDictionary getCatalog(PdfIndirectReference rootObj) {
   try {
     PdfDictionary theCat = pdf.getCatalog(rootObj);
     if (fieldArray == null) {
       if (acroForm != null) theCat.put(PdfName.ACROFORM, acroForm);
     } else addFieldResources(theCat);
     return theCat;
   } catch (IOException e) {
     throw new ExceptionConverter(e);
   }
 }
  private String extractTextFromPdf(byte pdfAsByteArray[]) throws IOException, IOException {
    PdfReader reader = new PdfReader(pdfAsByteArray);
    TextRenderListener listener = new TextRenderListener();
    PdfContentStreamProcessor processor = new PdfContentStreamProcessor(listener);
    PdfDictionary pageDic = reader.getPageN(1);
    PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES);

    byte array[] = ContentByteUtils.getContentBytesForPage(reader, 1);
    processor.processContent(array, resourcesDic);

    return listener.getSb();
  }
Beispiel #13
0
 /**
  * Launches an application or a document.
  *
  * @param application the application to be launched or the document to be opened or printed.
  * @param parameters (Windows-specific) A parameter string to be passed to the application. It can
  *     be <CODE>null</CODE>.
  * @param operation (Windows-specific) the operation to perform: "open" - Open a document, "print"
  *     - Print a document. It can be <CODE>null</CODE>.
  * @param defaultDir (Windows-specific) the default directory in standard DOS syntax. It can be
  *     <CODE>null</CODE>.
  */
 public PdfAction(String application, String parameters, String operation, String defaultDir) {
   put(PdfName.S, PdfName.LAUNCH);
   if (parameters == null && operation == null && defaultDir == null)
     put(PdfName.F, new PdfString(application));
   else {
     PdfDictionary dic = new PdfDictionary();
     dic.put(PdfName.F, new PdfString(application));
     if (parameters != null) dic.put(PdfName.P, new PdfString(parameters));
     if (operation != null) dic.put(PdfName.O, new PdfString(operation));
     if (defaultDir != null) dic.put(PdfName.D, new PdfString(defaultDir));
     put(PdfName.WIN, dic);
   }
 }
 @Override
 protected PdfDictionary getCatalog(PdfIndirectReference rootObj) {
   try {
     PdfDictionary cat = pdf.getCatalog(rootObj);
     if (form != null) {
       PdfIndirectReference ref = addToBody(form).getIndirectReference();
       cat.put(PdfName.ACROFORM, ref);
     }
     return cat;
   } catch (IOException e) {
     throw new ExceptionConverter(e);
   }
 }
Beispiel #15
0
 private Image indexedModel(byte bdata[], int bpc, int paletteEntries) throws BadElementException {
   Image img = new ImgRaw(width, height, 1, bpc, bdata);
   PdfArray colorspace = new PdfArray();
   colorspace.add(PdfName.INDEXED);
   colorspace.add(PdfName.DEVICERGB);
   byte np[] = getPalette(paletteEntries);
   int len = np.length;
   colorspace.add(new PdfNumber(len / 3 - 1));
   colorspace.add(new PdfString(np));
   PdfDictionary ad = new PdfDictionary();
   ad.put(PdfName.COLORSPACE, colorspace);
   img.setAdditional(ad);
   return img;
 }
Beispiel #16
0
 /** convenience method. Given a reader, set our "globals" */
 protected void setFromReader(PdfReader reader) {
   this.reader = reader;
   indirects = indirectMap.get(reader);
   if (indirects == null) {
     indirects = new HashMap<RefKey, IndirectReferences>();
     indirectMap.put(reader, indirects);
     PdfDictionary catalog = reader.getCatalog();
     PRIndirectReference ref = null;
     PdfObject o = catalog.get(PdfName.ACROFORM);
     if (o == null || o.type() != PdfObject.INDIRECT) return;
     ref = (PRIndirectReference) o;
     if (acroForm == null) acroForm = body.getPdfIndirectReference();
     indirects.put(new RefKey(ref), new IndirectReferences(acroForm));
   }
 }
 private static String getCOName(PdfReader reader, PRIndirectReference ref) {
   String name = "";
   while (ref != null) {
     PdfObject obj = PdfReader.getPdfObject(ref);
     if (obj == null || obj.type() != PdfObject.DICTIONARY) break;
     PdfDictionary dic = (PdfDictionary) obj;
     PdfString t = dic.getAsString(PdfName.T);
     if (t != null) {
       name = t.toUnicodeString() + "." + name;
     }
     ref = (PRIndirectReference) dic.get(PdfName.PARENT);
   }
   if (name.endsWith(".")) name = name.substring(0, name.length() - 1);
   return name;
 }
 /** Creates the new PDF by merging the fields and forms. */
 protected void closeIt() throws IOException {
   for (int k = 0; k < readers.size(); ++k) {
     readers.get(k).removeFields();
   }
   for (int r = 0; r < readers.size(); ++r) {
     PdfReader reader = readers.get(r);
     for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
       pageRefs.add(getNewReference(reader.getPageOrigRef(page)));
       pageDics.add(reader.getPageN(page));
     }
   }
   mergeFields();
   createAcroForms();
   for (int r = 0; r < readers.size(); ++r) {
     PdfReader reader = readers.get(r);
     for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
       PdfDictionary dic = reader.getPageN(page);
       PdfIndirectReference pageRef = getNewReference(reader.getPageOrigRef(page));
       PdfIndirectReference parent = root.addPageRef(pageRef);
       dic.put(PdfName.PARENT, parent);
       propagate(dic, pageRef, false);
     }
   }
   for (Map.Entry<PdfReader, IntHashtable> entry : readers2intrefs.entrySet()) {
     PdfReader reader = entry.getKey();
     try {
       file = reader.getSafeFile();
       file.reOpen();
       IntHashtable t = entry.getValue();
       int keys[] = t.toOrderedKeys();
       for (int k = 0; k < keys.length; ++k) {
         PRIndirectReference ref = new PRIndirectReference(reader, keys[k]);
         addToBody(PdfReader.getPdfObjectRelease(ref), t.get(keys[k]));
       }
     } finally {
       try {
         file.close();
         // TODO: Removed - the user should be responsible for closing all PdfReaders.  But, this
         // could cause a lot of memory leaks in code out there that hasn't been properly closing
         // things - maybe add a finalizer to PdfReader that calls PdfReader#close() ??
         //                    reader.close();
       } catch (Exception e) {
         // empty on purpose
       }
     }
   }
   pdf.close();
 }
Beispiel #19
0
 /**
  * Retrieves the page labels from a PDF as an array of {@link PdfPageLabelFormat} objects.
  *
  * @param reader a PdfReader object that has the page labels you want to retrieve
  * @return a PdfPageLabelEntry array, containing an entry for each format change or <code>null
  *     </code> if no page labels are present
  */
 public static PdfPageLabelFormat[] getPageLabelFormats(PdfReader reader) {
   PdfDictionary dict = reader.getCatalog();
   PdfDictionary labels =
       (PdfDictionary) PdfReader.getPdfObjectRelease(dict.get(PdfName.PAGELABELS));
   if (labels == null) return null;
   HashMap<Integer, PdfObject> numberTree = PdfNumberTree.readTree(labels);
   Integer numbers[] = new Integer[numberTree.size()];
   numbers = numberTree.keySet().toArray(numbers);
   Arrays.sort(numbers);
   PdfPageLabelFormat[] formats = new PdfPageLabelFormat[numberTree.size()];
   String prefix;
   int numberStyle;
   int pagecount;
   for (int k = 0; k < numbers.length; ++k) {
     Integer key = numbers[k];
     PdfDictionary d = (PdfDictionary) PdfReader.getPdfObjectRelease(numberTree.get(key));
     if (d.contains(PdfName.ST)) {
       pagecount = ((PdfNumber) d.get(PdfName.ST)).intValue();
     } else {
       pagecount = 1;
     }
     if (d.contains(PdfName.P)) {
       prefix = ((PdfString) d.get(PdfName.P)).toUnicodeString();
     } else {
       prefix = "";
     }
     if (d.contains(PdfName.S)) {
       char type = ((PdfName) d.get(PdfName.S)).toString().charAt(1);
       switch (type) {
         case 'R':
           numberStyle = UPPERCASE_ROMAN_NUMERALS;
           break;
         case 'r':
           numberStyle = LOWERCASE_ROMAN_NUMERALS;
           break;
         case 'A':
           numberStyle = UPPERCASE_LETTERS;
           break;
         case 'a':
           numberStyle = LOWERCASE_LETTERS;
           break;
         default:
           numberStyle = DECIMAL_ARABIC_NUMERALS;
           break;
       }
     } else {
       numberStyle = EMPTY;
     }
     formats[k] = new PdfPageLabelFormat(key.intValue() + 1, numberStyle, prefix, pagecount);
   }
   return formats;
 }
  private File convertPdfToPdfA(final InputStream source) throws IOException, DocumentException {

    final File pdfAFile =
        TempFileProvider.createTempFile("digitalSigning-" + System.currentTimeMillis(), ".pdf");

    // Reads a PDF document.
    PdfReader reader = new PdfReader(source);
    // PdfStamper: Applies extra content to the pages of a PDF document. This extra content can be
    // all the objects allowed in
    // PdfContentByte including pages from other Pdfs.
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdfAFile));
    // A generic Document class.
    Document document = new Document();
    // we create a writer that listens to the document
    PdfWriter writer = stamper.getWriter();
    int numberPages = reader.getNumberOfPages();
    writer.setPDFXConformance(PdfWriter.PDFA1A);
    document.open();

    // PdfDictionary:A dictionary is an associative table containing pairs of objects.
    // The first element of each pair is called the key and the second  element is called the value
    // <CODE>PdfName</CODE> is an object that can be used as a name in a PDF-file
    PdfDictionary outi = new PdfDictionary(PdfName.OUTPUTINTENT);
    outi.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1"));
    outi.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1"));
    outi.put(PdfName.S, PdfName.GTS_PDFA1);
    writer.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(outi));

    // Add pages
    PdfImportedPage p = null;
    Image image;
    for (int i = 0; i < numberPages; i++) {
      p = writer.getImportedPage(reader, i + 1);
      image = Image.getInstance(p);
      document.add(image);
    }
    writer.createXmpMetadata();

    document.close();

    // Add Metadata from source pdf
    HashMap<String, String> info = reader.getInfo();
    stamper.setMoreInfo(info);
    stamper.close();

    return pdfAFile;
  }
 /**
  * If the child of a structured element is a dictionary, we inspect the child; we may also draw a
  * tag.
  *
  * @param k the child dictionary to inspect
  */
 public void inspectChildDictionary(PdfDictionary k) throws IOException {
   if (k == null) return;
   PdfName s = k.getAsName(PdfName.S);
   if (s != null) {
     String tagN = PdfName.decodeName(s.toString());
     String tag = fixTagName(tagN);
     out.print("<");
     out.print(tag);
     out.print(">");
     PdfDictionary dict = k.getAsDict(PdfName.PG);
     if (dict != null) parseTag(tagN, k.getDirectObject(PdfName.K), dict);
     inspectChild(k.get(PdfName.K));
     out.print("</");
     out.print(tag);
     out.println(">");
   } else inspectChild(k.get(PdfName.K));
 }
 /** @since 2.1.5; before 2.1.5 the method was private */
 protected void updateCalculationOrder(PdfReader reader) {
   PdfDictionary catalog = reader.getCatalog();
   PdfDictionary acro = catalog.getAsDict(PdfName.ACROFORM);
   if (acro == null) return;
   PdfArray co = acro.getAsArray(PdfName.CO);
   if (co == null || co.size() == 0) return;
   AcroFields af = reader.getAcroFields();
   for (int k = 0; k < co.size(); ++k) {
     PdfObject obj = co.getPdfObject(k);
     if (obj == null || !obj.isIndirect()) continue;
     String name = getCOName(reader, (PRIndirectReference) obj);
     if (af.getFieldItem(name) == null) continue;
     name = "." + name;
     if (calculationOrder.contains(name)) continue;
     calculationOrder.add(name);
   }
 }
 void propagate(PdfObject obj, PdfIndirectReference refo, boolean restricted) throws IOException {
   if (obj == null) return;
   //        if (refo != null)
   //            addToBody(obj, refo);
   if (obj instanceof PdfIndirectReference) return;
   switch (obj.type()) {
     case PdfObject.DICTIONARY:
     case PdfObject.STREAM:
       {
         PdfDictionary dic = (PdfDictionary) obj;
         for (PdfName key : dic.getKeys()) {
           if (restricted && (key.equals(PdfName.PARENT) || key.equals(PdfName.KIDS))) continue;
           PdfObject ob = dic.get(key);
           if (ob != null && ob.isIndirect()) {
             PRIndirectReference ind = (PRIndirectReference) ob;
             if (!setVisited(ind) && !isPage(ind)) {
               PdfIndirectReference ref = getNewReference(ind);
               propagate(PdfReader.getPdfObjectRelease(ind), ref, restricted);
             }
           } else propagate(ob, null, restricted);
         }
         break;
       }
     case PdfObject.ARRAY:
       {
         // PdfArray arr = new PdfArray();
         for (Iterator<PdfObject> it = ((PdfArray) obj).listIterator(); it.hasNext(); ) {
           PdfObject ob = it.next();
           if (ob != null && ob.isIndirect()) {
             PRIndirectReference ind = (PRIndirectReference) ob;
             if (!isVisited(ind) && !isPage(ind)) {
               PdfIndirectReference ref = getNewReference(ind);
               propagate(PdfReader.getPdfObjectRelease(ind), ref, restricted);
             }
           } else propagate(ob, null, restricted);
         }
         break;
       }
     case PdfObject.INDIRECT:
       {
         throw new RuntimeException(
             MessageLocalization.getComposedMessage("reference.pointing.to.reference"));
       }
   }
 }
Beispiel #24
0
  private static void crop(String input) throws Exception {
    String output = input.replace(".pdf", "-crop.pdf");
    PdfReader reader = new PdfReader(input);
    final int n = reader.getNumberOfPages();
    Rectangle pageSize = reader.getPageSize(1);

    System.out.println("Input page size: " + pageSize);
    float left = (pageSize.getWidth() - kTextWidth) / 2 - kMargin;
    float right = pageSize.getWidth() - left;
    float bottom = (pageSize.getHeight() - kTextHeight) / 2;
    float top = pageSize.getHeight() - bottom;
    PdfRectangle rect = new PdfRectangle(left, bottom + kOffset, right, top + kOffset);
    for (int i = 1; i <= n; i++) {
      PdfDictionary pageDict = reader.getPageN(i);
      pageDict.put(PdfName.CROPBOX, rect);
    }
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(output));
    stamper.close();
  }
Beispiel #25
0
 public PdfContentByte getOverContent() {
   if (over == null) {
     if (pageResources == null) {
       pageResources = new PageResources();
       PdfDictionary resources = pageN.getAsDict(PdfName.RESOURCES);
       pageResources.setOriginalResources(resources, cstp.namePtr);
     }
     over = new PdfCopy.StampContent(cstp, pageResources);
   }
   return over;
 }
 /**
  * Gets a list of X509CRL objects from a Document Security Store.
  *
  * @return a list of CRLs
  * @throws GeneralSecurityException
  * @throws IOException
  */
 public List<X509CRL> getCRLsFromDSS() throws GeneralSecurityException, IOException {
   List<X509CRL> crls = new ArrayList<X509CRL>();
   if (dss == null) return crls;
   PdfArray crlarray = dss.getAsArray(PdfName.CRLS);
   if (crlarray == null) return crls;
   CertificateFactory cf = CertificateFactory.getInstance("X.509");
   for (int i = 0; i < crlarray.size(); i++) {
     PRStream stream = (PRStream) crlarray.getAsStream(i);
     X509CRL crl =
         (X509CRL) cf.generateCRL(new ByteArrayInputStream(PdfReader.getStreamBytes(stream)));
     crls.add(crl);
   }
   return crls;
 }
Beispiel #27
0
  /**
   * Copy the acroform for an input document. Note that you can only have one, we make no effort to
   * merge them.
   *
   * @param reader The reader of the input file that is being copied
   * @throws IOException, BadPdfFormatException
   */
  public void copyAcroForm(PdfReader reader) throws IOException, BadPdfFormatException {
    setFromReader(reader);

    PdfDictionary catalog = reader.getCatalog();
    PRIndirectReference hisRef = null;
    PdfObject o = catalog.get(PdfName.ACROFORM);
    if (o != null && o.type() == PdfObject.INDIRECT) hisRef = (PRIndirectReference) o;
    if (hisRef == null) return; // bugfix by John Englar
    RefKey key = new RefKey(hisRef);
    PdfIndirectReference myRef;
    IndirectReferences iRef = indirects.get(key);
    if (iRef != null) {
      acroForm = myRef = iRef.getRef();
    } else {
      acroForm = myRef = body.getPdfIndirectReference();
      iRef = new IndirectReferences(myRef);
      indirects.put(key, iRef);
    }
    if (!iRef.getCopied()) {
      iRef.setCopied();
      PdfDictionary theForm = copyDictionary((PdfDictionary) PdfReader.getPdfObject(hisRef));
      addToBody(theForm, myRef);
    }
  }
Beispiel #28
0
  /**
   * Generates the font dictionary.
   *
   * @param descendant the descendant dictionary
   * @param subsetPrefix the subset prefix
   * @param toUnicode the ToUnicode stream
   * @return the stream
   */
  public PdfDictionary getFontBaseType(
      PdfIndirectReference descendant, String subsetPrefix, PdfIndirectReference toUnicode) {
    PdfDictionary dic = new PdfDictionary(PdfName.FONT);

    dic.put(PdfName.SUBTYPE, PdfName.TYPE0);
    // The PDF Reference manual advises to add -encoding to CID font names
    if (cff) dic.put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName + "-" + encoding));
    // dic.put(PdfName.BASEFONT, new PdfName(subsetPrefix+fontName));
    else dic.put(PdfName.BASEFONT, new PdfName(subsetPrefix + fontName));
    // dic.put(PdfName.BASEFONT, new PdfName(fontName));
    dic.put(PdfName.ENCODING, new PdfName(encoding));
    dic.put(PdfName.DESCENDANTFONTS, new PdfArray(descendant));
    if (toUnicode != null) dic.put(PdfName.TOUNICODE, toUnicode);
    return dic;
  }
 void createWidgets(ArrayList<Object> list, AcroFields.Item item) {
   for (int k = 0; k < item.size(); ++k) {
     list.add(item.getPage(k));
     PdfDictionary merged = item.getMerged(k);
     PdfObject dr = merged.get(PdfName.DR);
     if (dr != null)
       PdfFormField.mergeResources(resources, (PdfDictionary) PdfReader.getPdfObject(dr));
     PdfDictionary widget = new PdfDictionary();
     for (Object element : merged.getKeys()) {
       PdfName key = (PdfName) element;
       if (widgetKeys.containsKey(key)) widget.put(key, merged.get(key));
     }
     widget.put(iTextTag, new PdfNumber(item.getTabOrder(k).intValue() + 1));
     list.add(widget);
   }
 }
 /**
  * Gets OCSP responses from the Document Security Store.
  *
  * @return a list of BasicOCSPResp objects
  * @throws IOException
  * @throws GeneralSecurityException
  */
 public List<BasicOCSPResp> getOCSPResponsesFromDSS()
     throws IOException, GeneralSecurityException {
   List<BasicOCSPResp> ocsps = new ArrayList<BasicOCSPResp>();
   if (dss == null) return ocsps;
   PdfArray ocsparray = dss.getAsArray(PdfName.OCSPS);
   if (ocsparray == null) return ocsps;
   for (int i = 0; i < ocsparray.size(); i++) {
     PRStream stream = (PRStream) ocsparray.getAsStream(i);
     OCSPResp ocspResponse = new OCSPResp(PdfReader.getStreamBytes(stream));
     if (ocspResponse.getStatus() == 0)
       try {
         ocsps.add((BasicOCSPResp) ocspResponse.getResponseObject());
       } catch (OCSPException e) {
         throw new GeneralSecurityException(e);
       }
   }
   return ocsps;
 }