Example usage for com.lowagie.text.pdf PdfDictionary get

List of usage examples for com.lowagie.text.pdf PdfDictionary get

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfDictionary get.

Prototype

public PdfObject get(PdfName key) 

Source Link

Document

Returns the PdfObject associated to the specified key.

Usage

From source file:org.pdfsam.console.business.pdf.handlers.UnpackCmdExecutor.java

License:Open Source License

/**
 * Unpack/*from  www.  j  a  va2s. c om*/
 * @param filespec the dictionary
 * @param outPath output directory
 * @param overwrite if true overwrite if already exists
 * @return number of unpacked files
 * @throws IOException
 */
private int unpackFile(PdfDictionary filespec, File outPath, boolean overwrite) throws IOException {
    int retVal = 0;
    if (filespec != null) {
        PdfName type = (PdfName) PdfReader.getPdfObject(filespec.get(PdfName.TYPE));
        if (PdfName.F.equals(type) || PdfName.FILESPEC.equals(type)) {
            PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(filespec.get(PdfName.EF));
            PdfString fn = (PdfString) PdfReader.getPdfObject(filespec.get(PdfName.F));
            if (fn != null && ef != null) {
                LOG.debug("Unpacking file " + fn + " to " + outPath);
                File fLast = new File(fn.toUnicodeString());
                File fullPath = new File(outPath, fLast.getName());
                if (fullPath.exists()) {
                    //check if overwrite is allowed
                    if (overwrite) {
                        if (!fullPath.delete()) {
                            LOG.warn("Unable to overwrite " + fullPath.getAbsolutePath()
                                    + ", unable to unpack.");
                        }
                    } else {
                        LOG.warn("Cannot overwrite " + fullPath.getAbsolutePath()
                                + " (overwrite is false), unable to unpack.");
                    }
                } else {
                    PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
                    if (prs != null) {
                        byte b[] = PdfReader.getStreamBytes(prs);
                        FileOutputStream fout = new FileOutputStream(fullPath);
                        fout.write(b);
                        fout.close();
                        retVal = 1;
                    }
                }
            }
        }
    }
    return retVal;
}

From source file:org.sejda.impl.itext.component.PdfUnpacker.java

License:Apache License

private void unpack(Set<PdfDictionary> dictionaries) throws TaskIOException {
    for (PdfDictionary dictionary : dictionaries) {
        PdfName type = (PdfName) PdfReader.getPdfObject(dictionary.get(PdfName.TYPE));
        if (PdfName.F.equals(type) || PdfName.FILESPEC.equals(type)) {
            PdfDictionary ef = (PdfDictionary) PdfReader.getPdfObject(dictionary.get(PdfName.EF));
            PdfString fn = (PdfString) PdfReader.getPdfObject(dictionary.get(PdfName.F));
            if (fn != null && ef != null) {
                PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
                if (prs != null) {
                    File tmpFile = copyToTemporaryFile(prs);
                    outputWriter.addOutput(file(tmpFile).name(fn.toUnicodeString()));
                }//www. j  a  va2  s.  c  o m
            }
        }
    }
}

From source file:org.sejda.impl.itext.component.PdfUnpacker.java

License:Apache License

private Set<PdfDictionary> getEmbeddedFilesDictionaries(PdfReader reader) {
    Set<PdfDictionary> retSet = new NullSafeSet<PdfDictionary>();
    PdfDictionary catalog = reader.getCatalog();
    PdfDictionary names = (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.NAMES));
    if (names != null) {
        PdfDictionary embFiles = (PdfDictionary) PdfReader.getPdfObject(names.get(PdfName.EMBEDDEDFILES));
        if (embFiles != null) {
            @SuppressWarnings("unchecked")
            HashMap<String, PdfObject> embMap = PdfNameTree.readTree(embFiles);
            for (PdfObject value : embMap.values()) {
                retSet.add((PdfDictionary) PdfReader.getPdfObject(value));
            }//from  w  ww .  j  a v  a2s. c  o  m
        }
    }
    return retSet;
}

From source file:org.sejda.impl.itext.component.PdfUnpacker.java

License:Apache License

private Set<PdfDictionary> getFileAttachmentsDictionaries(PdfReader reader) {
    Set<PdfDictionary> retSet = new NullSafeSet<PdfDictionary>();
    for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
        PdfArray annots = (PdfArray) PdfReader.getPdfObject(reader.getPageN(k).get(PdfName.ANNOTS));
        if (annots != null) {
            for (@SuppressWarnings("unchecked")
            Iterator<PdfObject> iter = annots.listIterator(); iter.hasNext();) {
                PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(iter.next());
                PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE));
                if (PdfName.FILEATTACHMENT.equals(subType)) {
                    retSet.add((PdfDictionary) PdfReader.getPdfObject(annot.get(PdfName.FS)));
                }/*from   w  ww  .  ja v a  2  s . co  m*/
            }
        }
    }
    return retSet;
}

From source file:oscar.form.pharmaForms.formBPMH.pdf.PDFController.java

License:Open Source License

/**
 * Read the smart tags off of a pdf document and use them to 
 * extract the property values from a POJO Object.
 * //  ww  w .  j a va 2  s  .c  om
 * Assuming that the pdf input path has been preset.
 * 
 * @param data : data object that contains data.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private void addDataToPDF() {

    AcroFields acroFields = getStamper().getAcroFields();
    Map acroFieldsMap = acroFields.getFields();
    Iterator<String> acroFieldsIt = acroFieldsMap.keySet().iterator();
    String replaceWith = "";
    String key = "";
    String cleanKey = "";
    int fieldType;
    String[] appStates;
    AcroFields.Item acroField;
    PdfDictionary annots;
    Iterator itannots;

    while (acroFieldsIt.hasNext()) {

        key = acroFieldsIt.next().toString();
        cleanKey = key.replaceAll(STRING_FILTER, "");
        fieldType = acroFields.getFieldType(key);
        appStates = acroFields.getAppearanceStates(key);
        acroField = (Item) acroFieldsMap.get(key);
        annots = acroField.getWidget(0);

        _Logger.debug("Field Type: " + cleanKey + " = " + fieldType);

        itannots = annots.getKeys().iterator();
        while (itannots.hasNext()) {
            PdfName annotKey = (PdfName) itannots.next();
            _Logger.debug("ANNOT KEY: " + annotKey);
            _Logger.debug("ANNOT VALUE: " + annots.get(annotKey));
        }

        if (appStates.length > 0) {
            for (int i = 0; appStates.length > i; i++) {
                _Logger.debug("APPEARANCE STATE: " + appStates[i]);
            }
        }

        replaceWith = invokeValue(cleanKey);

        //count the characters and compare to limit.
        //         if(fieldType == AcroFields.FIELD_TYPE_TEXT) {
        //            replaceWith = contentSplicer(replaceWith, 30);
        //         }

        try {

            _Logger.debug("Replacement Key and Value: Key = " + cleanKey + " Value = " + replaceWith);

            acroFields.setField(cleanKey, replaceWith);

        } catch (IOException e) {
            _Logger.log(Level.FATAL,
                    "Failed to set method " + cleanKey + " with value " + replaceWith + " into PDF document",
                    e);
        } catch (DocumentException e) {
            _Logger.log(Level.FATAL,
                    "Failed to set method " + cleanKey + " with value " + replaceWith + " into PDF document",
                    e);
        }

    }

}

From source file:questions.forms.GetTextFields.java

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {/*from  w ww.ja va  2  s.  c o m*/
        PrintStream out = new PrintStream(new File(RESULT));

        PdfLister lister = new PdfLister(out);

        PdfReader reader = new PdfReader(RESOURCE);

        PdfDictionary root = reader.getCatalog();
        PdfDictionary acroform = root.getAsDict(PdfName.ACROFORM);

        out.println("These are the form's font dictionaries:");
        PdfDictionary fonts = acroform.getAsDict(PdfName.DR).getAsDict(PdfName.FONT);
        for (PdfName key : (Set<PdfName>) fonts.getKeys()) {
            lister.listDict((PdfDictionary) PdfReader.getPdfObject(fonts.get(key)));
        }
        out.println("--------------");

        out.println("This is the default appearance for the complete form:");
        lister.listAnyObject(PdfReader.getPdfObject(acroform.get(PdfName.DA)));
        out.println("--------------");

        AcroFields form = reader.getAcroFields();
        Map<String, Item> fields = form.getFields();
        Item item;
        for (String name : fields.keySet()) {
            out.println(name);
            if (form.getFieldType(name) == AcroFields.FIELD_TYPE_TEXT) {
                item = form.getFieldItem(name);
                PdfDictionary dict = (PdfDictionary) item.getMerged(0);

                out.println("This is the field's font dictionary:");
                fonts = dict.getAsDict(PdfName.DR).getAsDict(PdfName.FONT);
                for (PdfName key : (Set<PdfName>) fonts.getKeys()) {
                    lister.listDict((PdfDictionary) PdfReader.getPdfObject(fonts.get(key)));
                }
                out.println("---");
                out.println("This is the field's default appearance");
                lister.listAnyObject(PdfReader.getPdfObject(dict.get(PdfName.DA)));
            } else {
                out.println("NOT A TEXT FIELD!");
            }
            out.println("--------------");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:questions.images.ResizeImage.java

public static void resizeImagesInPage(PdfReader reader, int page, float factor) throws IOException {
    PdfDictionary pageDictionary = reader.getPageN(page);
    PdfDictionary resources = (PdfDictionary) PdfReader.getPdfObject(pageDictionary.get(PdfName.RESOURCES));
    PdfDictionary xobjects = (PdfDictionary) PdfReader.getPdfObject(resources.get(PdfName.XOBJECT));
    if (xobjects != null) {
        for (Object xObjectKey : xobjects.getKeys()) {
            PdfName xobjectName = (PdfName) xObjectKey;
            PdfObject xobj = xobjects.get(xobjectName);
            PRStream imageStream = (PRStream) PdfReader.getPdfObject(xobj);
            PdfName subtype = (PdfName) PdfReader.getPdfObject(imageStream.get(PdfName.SUBTYPE));
            PdfName filter = (PdfName) PdfReader.getPdfObject(imageStream.get(PdfName.FILTER));
            if (PdfName.IMAGE.equals(subtype) && PdfName.DCTDECODE.equals(filter)) {
                BufferedImage src = ImageIO
                        .read(new ByteArrayInputStream(PdfReader.getStreamBytesRaw(imageStream)));
                int width = (int) (src.getWidth() * factor);
                int height = (int) (src.getHeight() * factor);
                BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                AffineTransform at = AffineTransform.getScaleInstance(factor, factor);
                Graphics2D g = dest.createGraphics();
                g.drawRenderedImage(src, at);
                ByteArrayOutputStream newImage = new ByteArrayOutputStream();
                ImageIO.write(dest, "JPG", newImage);
                imageStream.setData(newImage.toByteArray(), false, PRStream.NO_COMPRESSION);
                imageStream.put(PdfName.WIDTH, new PdfNumber(width));
                imageStream.put(PdfName.HEIGHT, new PdfNumber(height));
                imageStream.put(PdfName.FILTER, PdfName.DCTDECODE);
            }/*  ww w. j  av a2  s.c  om*/
        }
    }
}

From source file:questions.metadata.ReplaceXMP.java

public static void alterXmp1() {
    try {//www.  ja v a2  s. c  o  m
        PdfReader reader = new PdfReader(ORIGINAL);
        PdfDictionary catalog = reader.getCatalog();
        PdfObject obj = catalog.get(PdfName.METADATA);
        PRStream stream = (PRStream) PdfReader.getPdfObject(obj);
        String metadata = new String(PdfReader.getStreamBytes(stream));
        metadata = metadata.replaceAll("Hello World", "Hello Universe");
        stream.setData(metadata.getBytes(), false);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT1));
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.stamppages.RemoveAttachmentAnnotations.java

public static void main(String[] args) throws IOException, DocumentException {
    createPdfWithAttachments();// w ww. j av  a 2  s  .c om
    PdfReader reader = new PdfReader(RESOURCE);
    PdfDictionary page;
    PdfDictionary annotation;
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        page = reader.getPageN(i);
        PdfArray annots = page.getAsArray(PdfName.ANNOTS);
        if (annots != null) {
            for (int j = annots.size() - 1; j >= 0; j--) {
                annotation = annots.getAsDict(j);
                if (PdfName.FILEATTACHMENT.equals(annotation.get(PdfName.SUBTYPE))) {
                    annots.remove(j);
                }
            }
        }
    }
    reader.removeUnusedObjects();
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
    stamper.close();
}