Example usage for com.itextpdf.text.pdf PdfReader PdfReader

List of usage examples for com.itextpdf.text.pdf PdfReader PdfReader

Introduction

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

Prototype

public PdfReader(final PdfReader reader) 

Source Link

Document

Creates an independent duplicate.

Usage

From source file:org.dihedron.crypto.operations.verify.pdf.PDFVerifier.java

License:Open Source License

@Override
public boolean verify(byte[] signed, byte[] data) throws CryptoException {
    boolean verified = false;
    try {//from  w  w  w  .j a  v  a 2s. co  m
        PdfReader reader = new PdfReader(signed);
        AcroFields af = reader.getAcroFields();
        ArrayList<String> names = af.getSignatureNames();
        for (String name : names) {
            logger.debug("signature name: {}", name);
            logger.debug("signature covers whole document: {}", af.signatureCoversWholeDocument(name));
            logger.debug("document revision: {} of {}", af.getRevision(name), af.getTotalRevisions());
            PdfPKCS7 pk = af.verifySignature(name);
            Calendar cal = pk.getSignDate();
            Certificate[] pkc = pk.getCertificates();
            logger.debug("subject: {}", PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
            logger.debug("revision modified: {}", !pk.verify());
            Object fails[] = PdfPKCS7.verifyCertificates(pkc, keyring.getKeyStore(), null, cal);
            if (fails == null) {
                logger.debug("certificates verified against the KeyStoreHelper");
                verified = true;
            } else {
                logger.warn("certificate failed: {}", fails[1]);
                verified = false;
            }
        }
    } catch (IOException e) {
        throw new CryptoException("I/O exception while verifying the signature", e);
    } catch (SignatureException e) {
        throw new CryptoException("Signature exception while verifying the signature", e);
    }
    return verified;
}

From source file:org.dspace.disseminate.CitationDocument.java

/**
 * Creates a/*from w ww  .ja va 2 s  . c om*/
 * cited document from the given bitstream of the given item. This
 * requires that bitstream is contained in item.
 * <p>
 * The Process for adding a cover page is as follows:
 * <ol>
 *  <li> Load source file into PdfReader and create a
 *     Document to put our cover page into.</li>
 *  <li> Create cover page and add content to it.</li>
 *  <li> Concatenate the coverpage and the source
 *     document.</li>
 * </p>
 *
 * @param bitstream The source bitstream being cited. This must be a PDF.
 * @param cMeta The citation information used to generate the coverpage.
 * @return The temporary File that is the finished, cited document.
 * @throws com.itextpdf.text.DocumentException
 * @throws java.io.FileNotFoundException
 * @throws SQLException
 * @throws org.dspace.authorize.AuthorizeException
 */
private File makeCitedDocument(Bitstream bitstream, CitationMeta cMeta)
        throws DocumentException, IOException, SQLException, AuthorizeException {
    //Read the source bitstream
    PdfReader source = new PdfReader(bitstream.retrieve());

    Document citedDoc = new Document(PageSize.LETTER);

    File coverTemp = File.createTempFile(bitstream.getName(), ".cover.pdf");

    //Need a writer instance to make changed to the document.
    PdfWriter writer = PdfWriter.getInstance(citedDoc, new FileOutputStream(coverTemp));

    //Call helper function to add content to the coverpage.
    this.generateCoverPage(citedDoc, writer, cMeta);

    //Create reader from finished cover page.
    PdfReader cover = new PdfReader(new FileInputStream(coverTemp));

    //Get page labels from source document
    String[] labels = PdfPageLabels.getPageLabels(source);

    //Concatenate the finished cover page with the source document.
    File citedTemp = File.createTempFile(bitstream.getName(), ".cited.pdf");
    OutputStream citedOut = new FileOutputStream(citedTemp);
    PdfConcatenate concat = new PdfConcatenate(citedOut);
    concat.open();

    //Is the citation-page the first page or last-page?
    if (isCitationFirstPage()) {
        //citation as cover page
        concat.addPages(cover);
        concat.addPages(source);
    } else {
        //citation as tail page
        concat.addPages(source);
        concat.addPages(cover);
    }

    //Put all of our labels in from the orignal document.
    if (labels != null) {
        PdfPageLabels citedPageLabels = new PdfPageLabels();
        log.debug("Printing arbitrary page labels.");

        for (int i = 0; i < labels.length; i++) {
            citedPageLabels.addPageLabel(i + 1, PdfPageLabels.EMPTY, labels[i]);
            log.debug("Label for page: " + (i + 1) + " -> " + labels[i]);
        }
        citedPageLabels.addPageLabel(labels.length + 1, PdfPageLabels.EMPTY, "Citation Page");
        concat.getWriter().setPageLabels(citedPageLabels);
    }

    //Close it up
    concat.close();

    //Close the cover-page
    writer.close();
    coverTemp.delete();

    citedTemp.deleteOnExit();
    return citedTemp;
}

From source file:org.dspace.disseminate.CitationDocument.java

/**
 * Attempts to add a Logo to the document from the given resource. Returns
 * true on success and false on failure.
 *
 * @param doc The document to add the logo to. (Added to the top right
 * corner of the first page./*from   w  w  w  .  j a va  2 s  . c o  m*/
 * @param writer The writer associated with the given Document.
 * @param res The resource/path to the logo file. This file can be any of
 * the following formats:
 *  GIF, PNG, JPEG, PDF
 *
 * @return Succesfully added logo to document.
 */
private boolean addLogoToDocument(Document doc, PdfWriter writer, String res) {
    boolean ret = false;
    try {
        //First we try to get the logo as if it is a Java Resource
        URL logoURL = this.getClass().getResource(res);
        log.debug(res + " -> " + logoURL.toString());
        if (logoURL == null) {
            logoURL = new URL(res);
        }

        if (logoURL != null) {
            String mtype = URLConnection.guessContentTypeFromStream(logoURL.openStream());
            if (mtype == null) {
                mtype = URLConnection.guessContentTypeFromName(res);
            }
            log.debug("Determined MIMETYPE of logo: " + mtype);
            if (PDF_MIMES.contains(mtype)) {
                //Handle pdf logos.
                PdfReader reader = new PdfReader(logoURL);
                PdfImportedPage logoPage = writer.getImportedPage(reader, 1);
                Image logo = Image.getInstance(logoPage);
                float x = doc.getPageSize().getWidth() - doc.rightMargin() - logo.getScaledWidth();
                float y = doc.getPageSize().getHeight() - doc.topMargin() - logo.getScaledHeight();
                logo.setAbsolutePosition(x, y);
                doc.add(logo);
                ret = true;
            } else if (RASTER_MIMES.contains(mtype)) {
                //Use iText's Image class
                Image logo = Image.getInstance(logoURL);

                //Determine the position of the logo (upper-right corner) and
                //place it there.
                float x = doc.getPageSize().getWidth() - doc.rightMargin() - logo.getScaledWidth();
                float y = doc.getPageSize().getHeight() - doc.topMargin() - logo.getScaledHeight();
                logo.setAbsolutePosition(x, y);
                writer.getDirectContent().addImage(logo);
                ret = true;
            } else if (SVG_MIMES.contains(mtype)) {
                //Handle SVG Logos
                log.error("SVG Logos are not supported yet.");
            } else {
                //Cannot use other mimetypes
                log.debug("Logo MIMETYPE is not supported.");
            }
        } else {
            log.debug("Could not create URL to Logo resource: " + res);
        }
    } catch (Exception e) {
        log.error("Could not add logo (" + res + ") to cited document: " + e.getMessage());
        ret = false;
    }
    return ret;
}

From source file:org.ednovo.gooru.domain.service.resource.ResourceServiceImpl.java

License:Open Source License

private static List<String> splitToChaptersAndSaveFiles(String newLocalUrl) {
    try {//from  w  w w  . j  ava2  s  . co  m

        HashMap<Integer, String> chapters = new HashMap<Integer, String>();
        ArrayList<Integer> pages = new ArrayList<Integer>();

        /** Call the split method with filename and page size as params **/
        PdfReader reader = new PdfReader(newLocalUrl);
        reader.consolidateNamedDestinations();
        List<HashMap<String, Object>> list = SimpleBookmark.getBookmark(reader);

        for (HashMap<String, Object> test : list) {
            String page = test.get(PAGE).toString();
            Integer num = Integer.parseInt(page.substring(0, page.indexOf(' ')));
            chapters.put(num, (String) test.get(_TITLE));
            pages.add(num);
        }

        int index = 1;
        List<String> chaptersUrls = new ArrayList<String>();
        for (Integer i : pages) {
            String chapterUrl = null;
            if (pages.size() != index) {
                chapterUrl = splitAndSaveChapter(newLocalUrl, i, pages.get(index), chapters.get(i));
            } else {
                chapterUrl = splitAndSaveChapter(newLocalUrl, i, reader.getNumberOfPages(), chapters.get(i));
            }
            index++;

            if (chapterUrl != null) {
                chaptersUrls.add(chapterUrl);
            }
        }
        return chaptersUrls;
    } catch (Exception ex) {
        return new ArrayList<String>();
    }
}

From source file:org.ednovo.gooru.domain.service.resource.ResourceServiceImpl.java

License:Open Source License

/**
 * @param mainFileUrl//from  w  ww .  ja v a2s .co  m
 *            : PDF file that has to be splitted
 * @param splittedPageSize
 *            : Page size of each splitted files
 */
private static String splitAndSaveChapter(String mainFileUrl, int pageBeginNum, int pageEndNum, String name) {
    try {
        PdfReader reader = new PdfReader(mainFileUrl);

        int splittedPageSize = pageEndNum - pageBeginNum + 1;
        int pageNum = pageBeginNum;

        String chapterUrl = mainFileUrl.substring(0, mainFileUrl.indexOf(DOT_PDF)) + "-" + name + DOT_PDF;

        Document document = new Document(reader.getPageSizeWithRotation(1));

        FileOutputStream fos = new FileOutputStream(chapterUrl);
        PdfCopy writer = new PdfCopy(document, fos);
        Map<String, String> info = reader.getInfo();

        document.open();
        if ((info != null) && (info.get(_AUTHOR) != null)) {
            document.addAuthor(info.get(_AUTHOR));
        }

        document.addTitle(name);

        for (int offset = 0; offset < splittedPageSize && (pageNum + offset) < pageEndNum; offset++) {
            PdfImportedPage page = writer.getImportedPage(reader, pageNum + offset);
            writer.addPage(page);
        }

        document.close();
        writer.close();
        return chapterUrl;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.freemedsoftware.util.CompositePdfForm.java

License:Open Source License

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;//from  w  ww  .  j  av  a  2 s. c  o m
    try {
        line = parser.parse(getOptions(), args);
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        System.exit(1);
    }

    String dataFile = line.getOptionValue("i");
    String templateFile = line.getOptionValue("t");
    String outputFile = line.getOptionValue("o");

    if (dataFile == null || templateFile == null || outputFile == null) {
        System.err.println("options:");
        System.err.println("\t[-i|--input]     Input file name");
        System.err.println("\t[-t|--template]  PDF template");
        System.err.println("\t[-o|--output]    Output file name");
        System.exit(1);
    }

    if (!(new File(dataFile).exists())) {
        System.err.println("Could not open input data file " + dataFile);
        System.exit(1);
    }

    if (!(new File(templateFile).exists())) {
        System.err.println("Could not open template file " + templateFile);
        System.exit(1);
    }

    Serializer serializer = new Persister();
    FormElementList elementList = serializer.read(FormElementList.class, new File(dataFile));

    PdfReader templateReader = new PdfReader(templateFile);
    PdfStamper stamper = new PdfStamper(templateReader, new FileOutputStream(outputFile));

    // Iterate
    fillForm(stamper.getAcroFields(), elementList);

    stamper.close();
    System.exit(0);
}

From source file:org.gmdev.pdftrick.engine.CheckFiles.java

License:Open Source License

/**
 * method that check is single pdf has a User password protected, set userProtection = true if BadPasswordException;
 * @param File//from  www. ja  va2s.com
 */
private void hasProtection(File file) {
    PdfReader reader = null;
    try {
        reader = new PdfReader(file.getPath());
        if (reader != null) {
            if (reader.isEncrypted()) {
                ownerProtection = true;
            }
            reader.close();
        }
    } catch (BadPasswordException e) {
        userProtection = true;
    } catch (IOException e) {
        logger.error("Exception", e);
        PdfTrickMessages.append("ERROR", Consts.SENDLOG_MSG);
    }
}

From source file:org.gmdev.pdftrick.engine.ImagesExtractor.java

License:Open Source License

/**
 * /*from   w  w  w . j  a v a  2  s.  co m*/
 * @param timeDirResult
 * @param resultFilePath
 * @param imageSelected
 * @param inlineImgSelected
 * @return TRUE if the extraction went good
 */
private boolean extractImgSel(String timeDirResult, String resultFilePath,
        HashMap<String, RenderedImageAttributes> imageSelected,
        HashMap<String, RenderedImageAttributes> inlineImgSelected) {

    final Properties messages = factory.getMessages();
    String result = timeDirResult + "/" + "Img_%s.%s";
    PdfReader reader = null;
    boolean retExtract = true;

    try {
        reader = new PdfReader(resultFilePath);
        Set<String> keys = imageSelected.keySet();
        Iterator<String> i = keys.iterator();
        int z = 1;
        while (i.hasNext()) {
            BufferedImage buff = null;
            String key = i.next();
            RenderedImageAttributes imgAttr = imageSelected.get(key);
            String flip = imgAttr.getFlip();
            String rotate = imgAttr.getRotate();
            int ref = imgAttr.getReference();

            PdfObject o = reader.getPdfObject(ref);
            PdfStream stream = (PdfStream) o;
            PdfImageObject io = null;
            try {
                io = new PdfImageObject((PRStream) stream);
            } catch (UnsupportedPdfException updfe) {
                try {
                    buff = CustomExtraImgReader.readIndexedPNG(ref, resultFilePath);
                    buff = PdfTrickUtils.adjustImage(buff, flip, rotate);
                    String type = "png";
                    String filename = String.format(result, z, type);
                    File outputfile = new File(filename);
                    ImageIO.write(buff, type, outputfile);
                } catch (Exception e) {
                    logger.error("Exception", e);
                    PdfTrickMessages.append("ERROR", Consts.SENDLOG_MSG);
                }
            }

            if (io != null) {
                String type = io.getFileType();
                String filename = String.format(result, z, type);
                BufferedImage buffPic = null;
                try {
                    if (type.equalsIgnoreCase("JBIG2")) {
                        buffPic = CustomExtraImgReader.readJBIG2(io);
                    } else {
                        buffPic = io.getBufferedImage();
                    }
                } catch (IIOException e) {
                    byte[] imageByteArray = io.getImageAsBytes();
                    try {
                        buffPic = CustomExtraImgReader.readCMYK_JPG(imageByteArray);
                    } catch (Exception ex) {
                        logger.error("Exception", e);
                        PdfTrickMessages.append("ERROR", Consts.SENDLOG_MSG);
                    }
                }

                // check if image contains a mask image
                BufferedImage buffMask = null;
                PdfDictionary imageDictionary = io.getDictionary();
                PRStream maskStream = (PRStream) imageDictionary.getAsStream(PdfName.SMASK);

                if (maskStream != null) {
                    // i have an smask object i check that is not a jpeg format, because this may cause some problem on offscreen rendering
                    // usually all imges with mask are png ... and there aren't problem, if image is jpg i discard the mask :)
                    if (!type.equalsIgnoreCase("jpg")) {
                        PdfImageObject maskImage = new PdfImageObject(maskStream);
                        buffMask = maskImage.getBufferedImage();

                        Image img = PdfTrickUtils.TransformGrayToTransparency(buffMask);
                        buff = PdfTrickUtils.ApplyTransparency(buffPic, img);
                    } else {
                        buff = buffPic;
                    }
                } else {
                    buff = buffPic;
                }

                if (buff != null) {
                    buff = PdfTrickUtils.adjustImage(buff, flip, rotate);

                    //particular cases of encoding
                    String encode = "";
                    if (type.equalsIgnoreCase("jp2")) {
                        encode = "jpeg 2000";
                    } else if (type.equalsIgnoreCase("jbig2")) {
                        encode = "jpeg";
                        filename = String.format(result, z, "jpg");
                    } else {
                        encode = type;
                    }

                    File outputfile = new File(filename);
                    ImageIO.write(buff, encode, outputfile);
                }
            }
            z++;
        }
        reader.close();
        if (inlineImgSelected.size() > 0) {
            extractInlineImgSel(timeDirResult, inlineImgSelected, z);
        }
        PdfTrickMessages.append("INFO", messages.getProperty("tmsg_19"));
    } catch (Exception e) {
        logger.error("Exception", e);
        PdfTrickMessages.append("ERROR", Consts.SENDLOG_MSG);
        retExtract = false;
    }
    return retExtract;
}

From source file:org.gmdev.pdftrick.render.PdfRenderLeft.java

License:Open Source License

/**
 * Render pdf resultfile thumbs in a left_panel, using threads pool
 *///from w ww.j  a va  2 s . com
public void pdfRender() {
    String imgPath = PdfTrickUtils.createImgFolder();
    int totPages = 0;

    // get the page number of the new generated pdf
    try {
        PdfReader reader = new PdfReader(factory.getResultFile());
        totPages = reader.getNumberOfPages();
        factory.setNumPages(totPages);
        reader.close();
    } catch (Exception e) {
        logger.error("Exception", e);
        PdfTrickMessages.append("ERROR", Consts.SENDLOG_MSG);
    }

    // system of thread that call native function and renderizing pdf cover in png images 
    boolean runPool = true;
    int division = totPages / 3;
    if (totPages < 3) {
        runPool = false;
        division = totPages;
    }

    DivisionThumb divisionThumbs = new DivisionThumb(division, imgPath);
    factory.gettContainer().setDivisionThumbs(divisionThumbs);

    Thread divisionThumbsThread = new Thread(divisionThumbs, "divisionThumbsThread");
    factory.gettContainer().setDivisionThumbsThread(divisionThumbsThread);
    divisionThumbsThread.start();

    if (runPool) {
        ExecPool execPool = new ExecPool(totPages, division, imgPath);
        factory.gettContainer().setExecPool(execPool);

        Thread execPoolThread = new Thread(execPool, "execPoolThread");
        factory.gettContainer().setExecPoolThread(execPoolThread);
        execPoolThread.start();
    }

    // thread that search and showing thumbnails 
    ShowThumbs showThumbs = new ShowThumbs();
    factory.gettContainer().setShowThumbs(showThumbs);

    Thread showThumbsThread = new Thread(showThumbs, "showThumbsThread");
    factory.gettContainer().setShowThumbsThread(showThumbsThread);
    showThumbsThread.start();
}

From source file:org.gmdev.pdftrick.thread.ImgThumb.java

License:Open Source License

/**
 * Render img thumbs contained in a page
 *//*from   ww  w.  j  a va 2 s . com*/
public void execute() {
    final Properties messages = factory.getMessages();
    final JPanel centerPanel = factory.getUserInterface().getCenter().getCenterPanel();

    SwingUtilities.invokeLater(new ManagePanelWait("thumb", "thumb_show"));
    try {
        PdfReader reader = null;
        ImageListenerShowThumb listener = null;

        reader = new PdfReader(factory.getResultFile());
        PdfReaderContentParser parser = new PdfReaderContentParser(reader);
        listener = new ImageListenerShowThumb(numberPage);

        parser.processContent(numberPage, listener);
        reader.close();

        String infoUnsupported = "";
        String infoAvailable = "";

        if (listener.getUnsupportedImage() > 0) {
            infoUnsupported = MessageFormat.format(messages.getProperty("dmsg_02"), numberPage);
        }
        if (listener.getNumImg() == 0) {
            final String noImgTitle = messages.getProperty("jmsg_08");
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JLabel noImageLabel = new JLabel(noImgTitle);
                    noImageLabel.setHorizontalAlignment(JLabel.CENTER);
                    noImageLabel.setVerticalAlignment(JLabel.CENTER);
                    noImageLabel.setFont(new Font("Verdana", 1, 20));
                    noImageLabel.setName("NoPicsImg");
                    centerPanel.setLayout(new GridBagLayout());
                    centerPanel.add(noImageLabel);
                    centerPanel.revalidate();
                    centerPanel.repaint();
                }
            });
            infoAvailable = MessageFormat.format(messages.getProperty("dmsg_03"), numberPage);
        } else {
            String t = listener.getNumImg() > 1 ? messages.getProperty("tmsg_15")
                    : messages.getProperty("tmsg_16");
            infoAvailable = listener.getNumImg() + " " + t;
        }
        PdfTrickMessages.append("INFO", infoUnsupported + infoAvailable);
    } catch (Exception e) {
        logger.error("Exception", e);
        PdfTrickMessages.append("ERROR", Consts.SENDLOG_MSG);
    }
    SwingUtilities.invokeLater(new ManagePanelWait("thumb", "thumb_hide"));
    finished = true;
}