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.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java

License:Apache License

/**
 * Applies a text watermark (current date, user name, etc, depending on
 * options)//from  www . ja  v  a2 s .c  om
 * 
 * @param reader
 * @param writer
 * @param options
 */
private void textAction(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader,
        Map<String, Object> options) {

    PdfStamper stamp = null;
    File tempDir = null;
    ContentWriter writer = null;
    String watermarkText;
    StringTokenizer st;
    Vector<String> tokens = new Vector<String>();

    try {
        // get a temp file to stash the watermarked PDF in before moving to
        // repo
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());

        // get the PDF input stream and create a reader for iText
        PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream());
        stamp = new PdfStamper(reader, new FileOutputStream(file));
        PdfContentByte pcb;

        // get the PDF pages and position
        String pages = (String) options.get(PARAM_PAGE);
        String position = (String) options.get(PARAM_POSITION);
        String depth = (String) options.get(PARAM_WATERMARK_DEPTH);

        // create the base font for the text stamp
        BaseFont bf = BaseFont.createFont((String) options.get(PARAM_WATERMARK_FONT), BaseFont.CP1250,
                BaseFont.EMBEDDED);

        // get watermark text and process template with model
        String templateText = (String) options.get(PARAM_WATERMARK_TEXT);
        Map<String, Object> model = buildWatermarkTemplateModel(actionedUponNodeRef);
        StringWriter watermarkWriter = new StringWriter();
        freemarkerProcessor.processString(templateText, model, watermarkWriter);
        watermarkText = watermarkWriter.getBuffer().toString();

        // tokenize watermark text to support multiple lines and copy tokens
        // to vector for re-use
        st = new StringTokenizer(watermarkText, "\r\n", false);
        while (st.hasMoreTokens()) {
            tokens.add(st.nextToken());
        }

        // stamp each page
        int numpages = reader.getNumberOfPages();
        for (int i = 1; i <= numpages; i++) {
            Rectangle r = reader.getPageSizeWithRotation(i);

            // if this is an under-text stamp, use getUnderContent.
            // if this is an over-text stamp, use getOverContent.
            if (depth.equals(DEPTH_OVER)) {
                pcb = stamp.getOverContent(i);
            } else {
                pcb = stamp.getUnderContent(i);
            }

            // set the font and size
            float size = Float.parseFloat((String) options.get(PARAM_WATERMARK_SIZE));
            pcb.setFontAndSize(bf, size);

            // only apply stamp to requested pages
            if (checkPage(pages, i, numpages)) {
                writeAlignedText(pcb, r, tokens, size, position);
            }
        }

        stamp.close();

        // Get a writer and prep it for putting it back into the repo
        //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination
        NodeRef destinationNode = createDestinationNode(file.getName(),
                (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef);
        writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT,
                true);
        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);

        // Put it in the repo
        writer.putContent(file);

        // delete the temp file
        file.delete();
    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }

        if (stamp != null) {
            try {
                stamp.close();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.arc42.pdfutil.PdfChecker.java

License:Open Source License

static int countPagesInPdf(String candidate) {

    // LOGGER.log(Level.INFO, System.getProperty("user.dir"));

    PdfReader reader = null;//from   ww  w. ja  v  a  2 s . c  o  m
    try {
        reader = new PdfReader(candidate);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Exception: file not found - therefore I cannot count pages", e);
    }

    return reader.getNumberOfPages();
}

From source file:org.arc42.pdfutil.PdfConcatenizer.java

License:Open Source License

/**
 * concats all files given in sourceFile
 *///from w ww  .j ava2s.co m
public void concatFiles() {
    Document document = new Document();
    try {
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(targetFileName));
        document.open();
        PdfReader reader;
        int nrOfPagesInCurrentFile;
        for (int i = 0; i < sourceFiles.size(); i++) {
            reader = new PdfReader(sourceFiles.get(i));

            nrOfPagesInCurrentFile = reader.getNumberOfPages();
            for (int page = 0; page < nrOfPagesInCurrentFile;) {
                copy.addPage(copy.getImportedPage(reader, ++page));
            }

            if (evenify && (nrOfPagesInCurrentFile % 2 == 1)) {
                addBlankPage(copy);
            }

        }
        document.close();
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Exception: wrong file you gave me, Yoda muttered...", e);
    } catch (BadPdfFormatException e) {
        LOGGER.log(Level.SEVERE, "Exception: Encountered bad pdf format", e);
    } catch (DocumentException e) {
        LOGGER.log(Level.SEVERE, "Exception: Something bad happened to the output document.", e);
    }

}

From source file:org.archive.modules.extractor.ExtractorPDFContent.java

License:Apache License

protected boolean innerExtract(CrawlURI curi) {
    PdfReader documentReader;/*from   w  w  w.j a  v  a  2s  .  co m*/
    ArrayList<String> uris = new ArrayList<String>();

    try {
        documentReader = new PdfReader(curi.getRecorder().getContentReplayInputStream());

        for (int i = 1; i <= documentReader.getNumberOfPages(); i++) { //Page numbers start at 1
            String pageParseText = extractPageText(documentReader, i);
            Matcher matcher = URLPattern.matcher(pageParseText);

            while (matcher.find()) {
                String prospectiveURL = pageParseText.substring(matcher.start(), matcher.end()).trim();

                //handle URLs wrapped in parentheses
                if (prospectiveURL.startsWith("(")) {
                    prospectiveURL = prospectiveURL.substring(1, prospectiveURL.length());
                    if (prospectiveURL.endsWith(")"))
                        prospectiveURL = prospectiveURL.substring(0, prospectiveURL.length() - 1);
                }

                uris.add(prospectiveURL);

                //parsetext URLs tend to end in a '.' if they are in a sentence, queue without trailing '.'
                if (prospectiveURL.endsWith(".") && prospectiveURL.length() > 2)
                    uris.add(prospectiveURL.substring(0, prospectiveURL.length() - 1));

                //Full regex allows newlines which seem to be common, also add match without newline in case we are wrong
                if (matcher.group(19) != null) {
                    String alternateURL = matcher.group(1) + "://"
                            + (matcher.group(2) != null ? matcher.group(2) : "") + matcher.group(6)
                            + matcher.group(13);

                    //Again, handle URLs wrapped in parentheses
                    if (prospectiveURL.startsWith("(") && alternateURL.endsWith(")"))
                        alternateURL = alternateURL.substring(0, alternateURL.length() - 1);

                    uris.add(alternateURL);
                }
            }
        }

    } catch (IOException e) {
        curi.getNonFatalFailures().add(e);
        return false;
    } catch (RuntimeException e) {
        curi.getNonFatalFailures().add(e);
        return false;
    }

    if (uris.size() < 1) {
        return true;
    }

    for (String uri : uris) {
        try {
            LinkContext lc = LinkContext.NAVLINK_MISC;
            Hop hop = Hop.NAVLINK;
            CrawlURI out = curi.createCrawlURI(uri, lc, hop);
            curi.getOutLinks().add(out);
        } catch (URIException e1) {
            logUriError(e1, curi.getUURI(), uri);
        }
    }

    numberOfLinksExtracted.addAndGet(uris.size());

    LOGGER.fine(curi + " has " + uris.size() + " links.");
    // Set flag to indicate that link extraction is completed.
    return true;
}

From source file:org.cejug.footprint.FootPrint.java

License:Open Source License

public FootPrint(Map<String, String> values, URL url) {
    this(values);
    try {//from w  ww .ja v  a  2 s .c  om
        this.reader = new PdfReader(url);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.cejug.footprint.FootPrint.java

License:Open Source License

public FootPrint(Map<String, String> values, InputStream inputStream) {
    this(values);
    try {/*from  w w  w .j a va2s .  co  m*/
        this.reader = new PdfReader(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.cejug.footprint.FootPrint.java

License:Open Source License

public FootPrint(Map<String, String> values, String templatePDF) {
    this(values);
    try {//from w  w w . ja va  2  s.  c  o m
        this.reader = new PdfReader(new FileInputStream(templatePDF));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.cejug.yougi.web.report.EventAttendeeCertificate.java

License:Open Source License

public void setCertificateTemplate(PdfWriter writer, String urlTemplate) throws IOException {
    writer.setPageEvent(this);

    PdfReader reader = new PdfReader(urlTemplate);
    page = writer.getImportedPage(reader, 1);
    canvas = writer.getDirectContent();//from   w  w  w  .j  a  v  a 2  s  .c o m
}

From source file:org.crossref.pdfmark.Main.java

License:Open Source License

public Main(String[] args) {
    if (args.length == 0) {
        printUsage();//from w w w  . j av a  2 s.co  m
        System.exit(2);
    }

    CmdLineParser parser = new CmdLineParser();
    Option provideXmpOp = parser.addStringOption('p', "xmp-file");
    Option overwriteOp = parser.addBooleanOption('f', "force");
    Option outputOp = parser.addStringOption('o', "output-dir");
    Option doiOp = parser.addStringOption('d', "doi");
    Option searchOp = parser.addBooleanOption('s', "search-for-doi");
    Option copyrightOp = parser.addBooleanOption("no-copyright");
    Option rightsOp = parser.addStringOption("rights-agent");
    Option apiKeyOp = parser.addStringOption("api-key");

    try {
        parser.parse(args);
    } catch (CmdLineParser.OptionException e) {
        printUsage();
        System.exit(2);
    }

    String optionalXmpPath = (String) parser.getOptionValue(provideXmpOp, "");
    String outputDir = (String) parser.getOptionValue(outputOp, "");
    String explicitDoi = (String) parser.getOptionValue(doiOp, "");
    boolean useTheForce = (Boolean) parser.getOptionValue(overwriteOp, Boolean.FALSE);
    boolean searchForDoi = (Boolean) parser.getOptionValue(searchOp, Boolean.FALSE);
    boolean noCopyright = (Boolean) parser.getOptionValue(copyrightOp, Boolean.FALSE);
    String rightsAgent = (String) parser.getOptionValue(rightsOp, "");
    String apiKey = (String) parser.getOptionValue(apiKeyOp, ApiKey.DEFAULT);

    if (!explicitDoi.equals("") && searchForDoi) {
        exitWithError(2, "-d and -s are mutually exclusive options.");
    }

    if (!outputDir.isEmpty() && !new File(outputDir).exists()) {
        exitWithError(2, "The output directory, '" + outputDir + "' does not exist.");
    }

    byte[] optionalXmpData = null;

    if (!optionalXmpPath.equals("")) {
        /* We will take XMP data from a file. */
        FileInfo xmpFile = FileInfo.readFileFully(optionalXmpPath);
        if (xmpFile.missing) {
            exitWithError(2, "Error: File '" + xmpFile.path + "' does not exist.");
        } else if (xmpFile.error != null) {
            exitWithError(2, "Error: Could not read '" + xmpFile.path + "' because of:\n" + xmpFile.error);
        }

        optionalXmpData = xmpFile.data;
    }

    grabber = new MetadataGrabber(apiKey);

    /* Now we're ready to merge our imported or generated XMP data with what
     * is already in each PDF. */

    for (String pdfFilePath : parser.getRemainingArgs()) {
        String outputPath = getOutFileName(pdfFilePath);

        /* Grab the leaf. */
        if (outputPath.contains(File.separator)) {
            String[] split = outputPath.split(File.separator);
            outputPath = split[split.length - 1];
        }

        if (!outputDir.isEmpty()) {
            outputPath = outputDir + File.separator + outputPath;
        } else {
            /* Output to the working directory. */
        }

        File pdfFile = new File(pdfFilePath);
        File outputFile = new File(outputPath);

        byte[] resolvedXmpData = null;

        if (!pdfFile.exists()) {
            exitWithError(2, "Error: File '" + pdfFilePath + "' does not exist.");
        }

        if (outputFile.exists() && !useTheForce) {
            exitWithError(2, "Error: File '" + outputPath + "' already exists.\nTry using -f (force).");
        }

        try {
            if (!useTheForce && isLinearizedPdf(new FileInputStream(pdfFile))) {
                exitWithError(2,
                        "Error: '" + pdfFilePath + "' is a" + " linearized PDF and force is not specified."
                                + " This tool will output non-linearized PDF."
                                + "\nIf you don't mind that, use -f (force).");
            }
        } catch (IOException e) {
            exitWithError(2, "Error: Could not determine linearization" + " because of:\n" + e);
        }

        if (!explicitDoi.equals("")) {
            resolvedXmpData = getXmpForDoi(explicitDoi, !noCopyright, rightsAgent);
        }

        try {
            new File(outputFile.getPath() + ".tmp").deleteOnExit();

            FileInputStream fileIn = new FileInputStream(pdfFile);
            FileOutputStream fileOut = new FileOutputStream(outputFile.getPath() + ".tmp");
            PdfReader reader = new PdfReader(fileIn);
            PdfStamper stamper = new PdfStamper(reader, fileOut);

            byte[] merged = reader.getMetadata();

            if (optionalXmpData != null) {
                merged = XmpUtils.mergeXmp(merged, optionalXmpData);
            }

            if (resolvedXmpData != null) {
                merged = XmpUtils.mergeXmp(merged, resolvedXmpData);
            }

            stamper.setXmpMetadata(merged);

            stamper.close();
            reader.close();

            fileIn = new FileInputStream(outputFile.getPath() + ".tmp");
            writeInfoDictionary(fileIn, outputFile.getPath(), merged);
        } catch (IOException e) {
            exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e);
        } catch (DocumentException e) {
            exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e);
        } catch (XmpException e) {
            exitWithError(2, "Error: Couldn't handle '" + pdfFilePath + "' because of:\n" + e);
        } catch (COSVisitorException e) {
            exitWithError(2, "Error: Couldn't write document info dictionary" + " because of:\n" + e);
        }
    }

    shutDown();
}

From source file:org.dihedron.crypto.operations.sign.pdf.PDFSigner.java

License:Open Source License

@Override
public void sign(InputStream input, OutputStream output) throws CryptoException {
    try {// w  ww.ja  v  a  2s .com
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = PdfStamper.createSignature(reader, output, '\0');
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        //appearance.setVisibleSignature("mySig");
        appearance.setReason("Signed with Dihedron WebSign - Digital Signature for the Web ver. "
                + Crypto.valueOf(Traits.VERSION));
        appearance.setLocation("Hidden Signature");

        appearance.setCrypto((PrivateKey) key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        if (mode == Mode.EXCLUSIVE) {
            appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
        }
        // TODO: no graphic signature mode enabled yet
        //      if (graphic) {
        //         appearance.setAcro6Layers(true);
        //         appearance.setSignatureGraphic(Image.getInstance(RESOURCE));
        //         appearance.setRenderingMode(
        //         PdfSignatureAppearance.RenderingMode.GRAPHIC);
        //      }      
        stamper.close();
    } catch (IOException e) {
        logger.error("I/O exception writing the PDF", e);
        throw new CryptoException("I/O exception writing the PDF", e);
    } catch (DocumentException e) {
        logger.error("invalid document: exception writing the PDF", e);
        throw new CryptoException("document exception writing the PDF", e);
    }
}