Example usage for com.lowagie.text.pdf PdfReader getPageN

List of usage examples for com.lowagie.text.pdf PdfReader getPageN

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfReader getPageN.

Prototype

public PdfDictionary getPageN(int pageNum) 

Source Link

Document

Gets the dictionary that represents a page.

Usage

From source file:eu.europa.cedefop.europass.jtool.util.ExtractAttachments.java

License:EUPL

/**
  * Extract the attachment file/*from  ww  w . jav a 2s  .co  m*/
  * @throws Exception
  */
public void execute() throws Exception {
    boolean hasAttachment = false;
    try {
        PdfReader reader = new PdfReader(in);
        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());
                    unpackFile(filespec);
                }
            }
        }
        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.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));
                hasAttachment = true;
                unpackFile(filespec);
            }
        }
    } catch (Exception e) {
        log.error("Error while extracting PDF attachements: " + e);
    }
    if (!hasAttachment)
        throw new Exception("PDF file does not have attachment.");
}

From source file:jPDFmelange.MelangeJFrame.java

License:Open Source License

/** 
 *  Main save method.//from   ww w  . j av  a2  s  . co m
 *  <p> 
 *  Saves all elements of the main list represented with its {@link MelangeJFrame#listContentMain content} 
 *  to the specified file.
 *  
 *   @param fileName name of file to save.
 *   @throws IOException on File IO error.
 *   @throws DocumentException on itext PDF error. 
 */
private void saveFile(String fileName) throws IOException, DocumentException {
    File file = new File(fileName);
    File tmpfile = File.createTempFile("Mixer", null, file.getParentFile());
    String bakFileName = fileName.substring(0, fileName.lastIndexOf('.')).concat(".bak");
    File bakfile = new File(bakFileName);

    //
    // prevent writing to a PDF that is blocked by the renderer.
    //
    jPanePreview.closePdfFile();

    // itext usage
    System.out.println("Writing new content to <" + tmpfile.getName() + ">");
    PdfReader reader = null;
    PdfDictionary dict = null;
    Document pdfDoc = new Document();
    PdfCopy writer = new PdfCopy(pdfDoc, new FileOutputStream(tmpfile));
    pdfDoc.open();
    PageNode node = null;
    for (int i = 0; i < listContentMain.size(); i++) {
        node = (PageNode) listContentMain.get(i);
        if (node.password == null)
            reader = new PdfReader(node.filename);
        else
            reader = new PdfReader(node.filename, node.password.getBytes());
        dict = reader.getPageN(node.pagenumber);
        dict.put(PdfName.ROTATE, new PdfNumber(node.rotation));
        writer.addPage(writer.getImportedPage(reader, node.pagenumber));
        reader.close(); // close input file
        System.out
                .println("Page " + node.pagenumber + "  File:" + node.filename + "  Rotation:" + node.rotation);
    }

    //
    // save page mode and layout preferences
    //
    if (jCheckBoxEnablePDFViewerPrefs.isSelected()) {

        String key = jPanelViewPrefs.getKeyPageMode();
        writer.setViewerPreferences(PageMode.get(key));

        key = jPanelViewPrefs.getKeyPageLayout();
        writer.setViewerPreferences(PageLayout.get(key));

        if (jPanelViewPrefs.jCheckBoxHideToolbar.isSelected())
            writer.addViewerPreference(PdfName.HIDETOOLBAR, PdfBoolean.PDFTRUE);
        if (jPanelViewPrefs.jCheckBoxHideMenubar.isSelected())
            writer.addViewerPreference(PdfName.HIDEMENUBAR, PdfBoolean.PDFTRUE);
        if (jPanelViewPrefs.jCheckBoxHideWindowUI.isSelected())
            writer.addViewerPreference(PdfName.HIDEWINDOWUI, PdfBoolean.PDFTRUE);
        if (jPanelViewPrefs.jCheckBoxFitWindow.isSelected())
            writer.addViewerPreference(PdfName.FITWINDOW, PdfBoolean.PDFTRUE);
        if (jPanelViewPrefs.jCheckBoxCenterWindow.isSelected())
            writer.addViewerPreference(PdfName.CENTERWINDOW, PdfBoolean.PDFTRUE);
        if (jPanelViewPrefs.jCheckBoxDisplayDocTitle.isSelected())
            writer.addViewerPreference(PdfName.DISPLAYDOCTITLE, PdfBoolean.PDFTRUE);
    }

    pdfDoc.close(); // close Helper Class
    writer.close(); // close output file

    // save old file to a XXX.bak file
    if (bakfile.exists())
        bakfile.delete();
    if (file.renameTo(bakfile.getCanonicalFile())) {
        System.out.println("Orginal File is saved in <" + bakfile.getName() + ">");
    }

    // move new content to original file name
    file = new File(fileName);
    if (tmpfile.renameTo(file))
        System.out.println("<" + tmpfile.getName() + "> is copied to <" + file.getName() + "> ");
    else {
        JOptionPane.showMessageDialog(MelangeJFrame.this,
                messages.getString("canNotWriteFile") + file.getName() + messages.getString("trySaveAs"),
                messages.getString("warning"), JOptionPane.WARNING_MESSAGE);
        System.out.println(
                messages.getString("canNotWriteFile") + file.getName() + messages.getString("trySaveAs"));
    }

}

From source file:net.sqs2.omr.master.sqm.PDFAttachmentExtractor.java

License:Apache License

@SuppressWarnings("unchecked")
private 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;
                }/*from  w w  w .j  a va2s. c o m*/
            }
        }
    }
    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;
}

From source file:net.sqs2.omr.master.sqm.PDFAttachmentToSQMTranslator.java

License:Apache License

private 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;
                }//ww  w.  j  a v  a 2 s.c om
            }
        }
    }
    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;
}

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void rotate(int pageCount, PdfPageData currentPageData, RotatePDFPages current_selection) {
    File tempFile = null;/*from  w  w w.  ja va  2s.  c om*/

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {
        int[] pgsToRotate = current_selection.getRotatedPages();

        if (pgsToRotate == null)
            return;

        int check = -1;

        if (pgsToRotate.length == 1) {
            check = currentGUI.showConfirmDialog(Messages.getMessage("PdfViewerMessage.ConfirmRotatePages"),
                    Messages.getMessage("PdfViewerMessage.Confirm"), JOptionPane.YES_NO_OPTION);
        } else {
            check = currentGUI.showConfirmDialog(Messages.getMessage("PdfViewerMessage.ConfirmRotatePages"),
                    Messages.getMessage("PdfViewerMessage.Confirm"), JOptionPane.YES_NO_OPTION);
        }

        if (check != 0)
            return;

        if (pgsToRotate == null)
            return;

        List pagesToRotate = new ArrayList();
        for (int i = 0; i < pgsToRotate.length; i++)
            pagesToRotate.add(new Integer(pgsToRotate[i]));

        int direction = current_selection.getDirection();

        PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        for (int page = 1; page <= pageCount; page++) {
            if (pagesToRotate.contains(new Integer(page))) {
                // int currentRotation =
                // Integer.parseInt(reader.getPageN(page).get(PdfName.ROTATE).toString());

                int currentRotation = currentPageData.getRotation(page);

                if (direction == ROTATECLOCKWISE)
                    reader.getPageN(page).put(PdfName.ROTATE, new PdfNumber((currentRotation + 90) % 360));
                else if (direction == ROTATECOUNTERCLOCKWISE)
                    reader.getPageN(page).put(PdfName.ROTATE, new PdfNumber((currentRotation - 90) % 360));
                else if (direction == ROTATE180)
                    reader.getPageN(page).put(PdfName.ROTATE, new PdfNumber((currentRotation + 180) % 360));
                else
                    throw new Exception("invalid desired rotation");
            }

        }

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));
        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void setCrop(int pageCount, PdfPageData currentPageData, CropPDFPages cropPage) {
    File tempFile = null;// w ww. j a  v a  2 s .c om

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {

        int[] pgsToEdit = cropPage.getPages();

        if (pgsToEdit == null)
            return;

        List pagesToEdit = new ArrayList();
        for (int i = 0; i < pgsToEdit.length; i++)
            pagesToEdit.add(new Integer(pgsToEdit[i]));

        PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        boolean applyToCurrent = cropPage.applyToCurrentCrop();

        for (int page = 1; page <= pageCount; page++) {
            if (pagesToEdit.contains(new Integer(page))) {

                float currentLeftCrop = currentPageData.getCropBoxX(page);
                float currentBottomCrop = currentPageData.getCropBoxY(page);
                float currentRightCrop = currentPageData.getCropBoxWidth(page) + currentLeftCrop;
                float currentTopCrop = currentPageData.getCropBoxHeight(page) + currentBottomCrop;

                float[] newCrop = cropPage.getCrop();

                if (applyToCurrent) {
                    newCrop[0] = currentLeftCrop + newCrop[0];
                    newCrop[1] = currentBottomCrop + newCrop[1];
                    newCrop[2] = currentRightCrop - newCrop[2];
                    newCrop[3] = currentTopCrop - newCrop[3];
                } else {
                    newCrop[2] = reader.getPageSize(page).width() - newCrop[2];
                    newCrop[3] = reader.getPageSize(page).height() - newCrop[3];
                }

                reader.getPageN(page).put(PdfName.CROPBOX, new PdfArray(newCrop));
            }
        }

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));
        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

From source file:org.kuali.coeus.propdev.impl.budget.subaward.PropDevPropDevBudgetSubAwardServiceImpl.java

License:Open Source License

/**
 * extracts attachments from PDF File//from  w  ww .  ja  v  a2s.co m
 */

@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;
}

From source file:org.kuali.coeus.propdev.impl.s2s.S2sUserAttachedFormServiceImpl.java

License:Open Source License

private 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(filespec);
                if (!fileMap.containsKey(fileInfo[0])) {
                    fileMap.put(fileInfo[0], fileInfo[1]);
                }//from w  w  w . j  ava  2  s .co m
            }
        }
    }
    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.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(filespec);
            if (fileMap.containsKey(fileInfo[0])) {
                throw new RuntimeException(DUPLICATE_FILE_NAMES);
            }
            fileMap.put(fileInfo[0], fileInfo[1]);
        }
    }

    return fileMap;
}

From source file:org.kuali.kra.s2s.service.impl.S2SUserAttachedFormServiceImpl.java

License:Educational Community License

private 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])) {
                    fileMap.put(fileInfo[0], fileInfo[1]);
                }//  w ww .  j  a  v  a2s. com
            }
        }
    }
    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.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;
}

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 . j  a  v  a 2s .  c  o m*/
            }
        }
    }
    return retSet;
}