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

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

Introduction

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

Prototype

public int getNumberOfPages() 

Source Link

Document

Gets the number of pages in the document.

Usage

From source file:managedbean.aas.reportController.java

public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {

    Document document = new Document();
    try {/*  www . ja v a 2  s  .  c o m*/
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the outputstream            
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
        // data

        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, 9);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                            "" + currentPageNumber + " of " + totalPages, 520, 5, 0);
                    cb.endText();
                }
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:mpv5.utils.export.Export.java

License:Open Source License

private static File mergeFiles(List<File> p) {

    Document document = new Document();
    try {/*  w  ww .j  ava 2s . c om*/
        List<InputStream> pdfs = new ArrayList<InputStream>();
        for (int i = 0; i < p.size(); i++) {
            File inputStream = p.get(i);
            pdfs.add(new FileInputStream(inputStream));
        }
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }

        File f = FileDirectoryHandler.getTempFile("pdf");
        FileOutputStream outputstream = new FileOutputStream(f);
        PdfWriter writer = PdfWriter.getInstance(document, outputstream);

        document.open();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

            }
            pageOfCurrentReaderPDF = 0;
        }
        outputstream.flush();
        document.close();
        outputstream.close();

        return f;
    } catch (Exception e) {
        Log.Debug(e);
    } finally {
        if (document.isOpen()) {
            document.close();
        }
    }

    return null;
}

From source file:net.laubenberger.bogatyr.helper.HelperPdf.java

License:Open Source License

/**
 * Returns the text of a given PDF as {@link String}.
 * //from w  w  w  .  j  a  v  a2s  . c o  m
 * @param file
 *           input as PDF
 * @return text of the given PDF
 * @throws IOException
 * @see File
 * @since 0.9.3
 */
public static String getText(final File file) throws IOException { // $JUnit$
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodStart(file));
    if (null == file) {
        throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$
    }

    final PdfReader pdfReader = new PdfReader(file.getAbsolutePath());
    final PdfTextExtractor pdfExtractor = new PdfTextExtractor(pdfReader);

    final StringBuilder sb = new StringBuilder();

    for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) {
        sb.append(pdfExtractor.getTextFromPage(page));
        sb.append(HelperString.NEW_LINE);
    }
    final String result = sb.toString();

    if (log.isDebugEnabled())
        log.debug(HelperLog.methodExit(result));
    return result;
}

From source file:net.mitnet.tools.pdf.book.pdf.builder.PdfBookBuilder.java

License:Open Source License

public void buildBook(List<File> inputFileList, File outputFile) {

    try {/*from   ww  w .  ja  v  a  2s  .  co m*/

        float pageWidth = getConfig().getPageWidth();
        float pageHeight = getConfig().getPageHeight();

        // Create new Document

        /*
        float marginLeft = 36;
        float marginRight = 36;
        float marginTop = 36;
        float marginBottom = 36;
        */

        if (isVerboseEnabled()) {
            verbose("Building output PDF file " + outputFile);
        }

        // TableOfContents toc = new TableOfContents();

        ProgressMonitor progressMonitor = getConfig().getProgressMonitor();
        TocRowChangeListener tocRowChangeListener = getConfig().getTocRowChangeListener();

        Document outputDocument = new Document(getConfig().getPageSize());
        // Document outputDocument = new Document( getPageSize(), marginLeft, marginRight, marginTop, marginBottom );

        PdfWriter pdfWriter = PdfWriter.getInstance(outputDocument, new FileOutputStream(outputFile));

        // TODO - review PDF page event forwarder
        PdfPageEventLogger pdfPageEventLogger = new PdfPageEventLogger();
        pdfWriter.setPageEvent(pdfPageEventLogger);

        outputDocument.open();

        String metaTitle = getConfig().getMetaTitle();
        if (!StringUtils.isEmpty(metaTitle)) {
            outputDocument.addTitle(metaTitle);
        }
        String metaAuthor = getConfig().getMetaAuthor();
        if (!StringUtils.isEmpty(metaAuthor)) {
            outputDocument.addAuthor(metaAuthor);
        }

        PdfContentByte pdfContent = pdfWriter.getDirectContent();

        // Loop through and pull pages
        int outputPageCount = 0;
        int currentSourceFileIndex = 0;
        int maxSourceFileIndex = inputFileList.size();

        // BaseFont pageLabelFont = BaseFont.createFont( PdfBookBuilderConfig.DEFAULT_FONT, BaseFont.CP1250, BaseFont.EMBEDDED );
        BaseFont pageLabelFont = BaseFont.createFont(PdfBookBuilderConfig.DEFAULT_FONT_PATH, BaseFont.CP1250,
                BaseFont.EMBEDDED);
        if (isVerboseEnabled()) {
            verbose("Using page label font " + pageLabelFont);
        }

        if (isVerboseEnabled()) {
            verbose("Assembling pages using n-up " + getConfig().getNup());
        }

        for (File sourceFile : inputFileList) {

            currentSourceFileIndex++;

            // TODO - refactor current file PDF page processing to another method
            // TODO - handle failover to ensure processing continues ???

            if (sourceFile.isFile()) {

                if (isVerboseEnabled()) {
                    verbose("Reading source PDF file " + sourceFile);
                }

                int sourcePageIndex = 0;

                PdfReader sourcePdfReader = new PdfReader(sourceFile.getCanonicalPath());
                PdfReaderHelper sourcePdfReaderHelper = new PdfReaderHelper(sourcePdfReader);
                if (isVerboseEnabled()) {
                    verbose("PDF reader is " + sourcePdfReader);
                    verbose("PDF reader helper is " + sourcePdfReaderHelper);
                }

                String currentSourcePdfTitle = FilenameUtils.getBaseName(sourceFile.getName());
                String currentSourcePdfAuthor = getSystemUserName();
                if (isVerboseEnabled()) {
                    verbose("PDF title is " + currentSourcePdfTitle);
                    verbose("PDF author is " + currentSourcePdfAuthor);
                }

                currentSourcePdfTitle = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfTitle);
                currentSourcePdfAuthor = sourcePdfReaderHelper.getDocumentTitle(currentSourcePdfAuthor);
                if (isVerboseEnabled()) {
                    verbose("PDF info title is " + currentSourcePdfTitle);
                    verbose("PDF info author is " + currentSourcePdfAuthor);
                }

                boolean firstPageOfCurrentSource = true;

                int maxSourcePages = sourcePdfReader.getNumberOfPages();
                if (isVerboseEnabled()) {
                    verbose("There are " + maxSourcePages + " page(s) in source PDF file " + sourceFile);
                }

                // process all pages from source doc
                while (sourcePageIndex < maxSourcePages) {

                    // add new page to current document
                    outputDocument.newPage();

                    outputPageCount++;
                    if (isVerboseEnabled()) {
                        verbose("Building output PDF page " + outputPageCount + " ...");
                    }

                    // add first page of current source to TOC listener
                    if (firstPageOfCurrentSource) {
                        int currentPageIndex = outputPageCount;
                        if (tocRowChangeListener != null) {
                            TocRow tocEntry = new TocRow(currentSourcePdfTitle, currentPageIndex);
                            tocRowChangeListener.addTocRow(tocEntry);
                            if (isVerboseEnabled()) {
                                verbose("Added TOC entry " + tocEntry + " to listener");
                            }
                        }
                        firstPageOfCurrentSource = false;
                    }

                    // extract first page from source document
                    sourcePageIndex++;
                    if (isVerboseEnabled()) {
                        verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages
                                + " from source to output");
                    }
                    PdfImportedPage page1 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex);

                    // n-up is 1
                    if (config.getNup() == 1) {
                        // add first page to top half of current page
                        // TODO - review magic transformation matrix numbers and offsets
                        // TODO - calculate scaling/transform based on page rect and template rect
                        float p1a = 0.65f;
                        float p1b = 0;
                        float p1c = 0;
                        float p1d = 0.65f;
                        float p1e = 20;
                        float p1f = 160;
                        pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f);

                        // n-up is 2 (default)
                    } else {

                        // add first page to top half of current page
                        // TODO - review magic transformation matrix numbers and offsets
                        float p1a = 0.5f;
                        float p1b = 0;
                        float p1c = 0;
                        float p1d = 0.5f;
                        float p1e = (125);
                        float p1f = ((pageWidth / 2) + 120 + 20);
                        pdfContent.addTemplate(page1, p1a, p1b, p1c, p1d, p1e, p1f);

                        // extract second page from source document ?
                        PdfImportedPage page2 = null;
                        if (sourcePageIndex < maxSourcePages) {
                            sourcePageIndex++;
                            if (isVerboseEnabled()) {
                                verbose("Adding page " + sourcePageIndex + " of " + maxSourcePages
                                        + " from source to output");
                            }
                            page2 = pdfWriter.getImportedPage(sourcePdfReader, sourcePageIndex);
                        }

                        // add second page to bottom half of current page
                        if (page2 != null) {
                            // TODO - review magic transformation matrix numbers and offsets
                            float p2a = 0.5f;
                            float p2b = 0;
                            float p2c = 0;
                            float p2d = 0.5f;
                            float p2e = 125;
                            float p2f = 120;
                            pdfContent.addTemplate(page2, p2a, p2b, p2c, p2d, p2e, p2f);
                        }
                    }

                    /*
                    // add first page to top half of current page
                    // TODO - review magic transformation matrix numbers and offsets
                    float p1a = 0.5f;
                    float p1b = 0;
                    float p1c = 0;
                    float p1d = 0.5f;
                    float p1e = (125);
                    float p1f = ((pageWidth / 2) + 120 + 20);
                    pdfContent.addTemplate( page1, p1a, p1b, p1c, p1d, p1e, p1f );
                            
                    // add second page to bottom half of current page
                    if (page2 != null) {
                       // TODO - review magic transformation matrix numbers and offsets
                       float p2a = 0.5f; 
                       float p2b = 0;
                       float p2c = 0;
                       float p2d = 0.5f;
                       float p2e = 125;
                       float p2f = 120;
                       pdfContent.addTemplate( page2, p2a, p2b, p2c, p2d, p2e, p2f );
                    }
                    */

                    // Add current page number to page footer
                    String pageCountLabel = "Page " + outputPageCount;
                    pdfContent.beginText();
                    pdfContent.setFontAndSize(pageLabelFont, PdfBookBuilderConfig.DEFAULT_FONT_SIZE);
                    pdfContent.showTextAligned(PdfContentByte.ALIGN_CENTER, pageCountLabel, (pageWidth / 2), 40,
                            0);
                    pdfContent.endText();
                }

                if (isVerboseEnabled()) {
                    verbose("Finished reading " + maxSourcePages + " page(s) from source PDF file "
                            + sourceFile);
                }

                // update progress
                if (isVerboseEnabled()) {
                    if (progressMonitor != null) {
                        int fileProgressPercentage = MathHelper.calculatePercentage(currentSourceFileIndex,
                                maxSourceFileIndex);
                        progressMonitor.setProgressPercentage(fileProgressPercentage);
                    }
                }
            }
        }

        // close document
        outputDocument.close();

        if (isVerboseEnabled()) {
            verbose("Output PDF file " + outputFile + " contains " + outputPageCount + " page(s)");
        }

        // TODO - output ODT page stats summary

    } catch (Exception e) {

        String msg = "Error building PDF book: " + e.getMessage();
        e.printStackTrace(System.err);
        System.err.println(msg);

    }

}

From source file:net.mitnet.tools.pdf.book.publisher.BookPublisher.java

License:Open Source License

/**
 * Returns the number of pages in a PDF file.
 * // ww  w  .j av  a2s.c o m
 * @param pdfFileName
 * @return
 * @throws IOException
 * 
 * @see http://stackoverflow.com/questions/6026971/page-count-of-pdf-with-java
 */
private int countPdfPages(String filename) throws IOException {
    PdfReader reader = new PdfReader(filename);
    int pageCount = reader.getNumberOfPages();
    reader.close();
    return pageCount;
}

From source file:net.sf.jsignpdf.PdfExtraInfo.java

License:Mozilla Public License

/**
 * Returns number of pages in PDF document. If error occures (file not found
 * or sth. similar) -1 is returned.//  w  w w.j  a va 2 s.  c om
 * 
 * @return number of pages (or -1 if error occures)
 */
public int getNumberOfPages() {
    int tmpResult = 0;
    PdfReader reader = null;
    try {
        try {
            reader = new PdfReader(options.getInFile(), options.getPdfOwnerPwdStrX().getBytes());
        } catch (Exception e) {
            try {
                reader = new PdfReader(options.getInFile(), new byte[0]);
            } catch (Exception e2) {
                // try to read without password
                reader = new PdfReader(options.getInFile());
            }
        }
        tmpResult = reader.getNumberOfPages();
    } catch (Exception e) {
        tmpResult = -1;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
            }
        }
    }

    return tmpResult;
}

From source file:net.sf.jsignpdf.SignerLogic.java

License:Mozilla Public License

/**
 * Signs a single file.//from   w w  w.j av a 2  s.  c  o  m
 * 
 * @return true when signing is finished succesfully, false otherwise
 */
public boolean signFile() {
    final String outFile = options.getOutFileX();
    if (!validateInOutFiles(options.getInFile(), outFile)) {
        LOGGER.info(RES.get("console.skippingSigning"));
        return false;
    }

    boolean finished = false;
    Throwable tmpException = null;
    FileOutputStream fout = null;
    try {
        SSLInitializer.init(options);

        final PrivateKeyInfo pkInfo = KeyStoreUtils.getPkInfo(options);
        final PrivateKey key = pkInfo.getKey();
        final Certificate[] chain = pkInfo.getChain();
        if (ArrayUtils.isEmpty(chain)) {
            // the certificate was not found
            LOGGER.info(RES.get("console.certificateChainEmpty"));
            return false;
        }
        LOGGER.info(RES.get("console.createPdfReader", options.getInFile()));
        PdfReader reader;
        try {
            reader = new PdfReader(options.getInFile(), options.getPdfOwnerPwdStrX().getBytes());
        } catch (Exception e) {
            try {
                reader = new PdfReader(options.getInFile(), new byte[0]);
            } catch (Exception e2) {
                // try to read without password
                reader = new PdfReader(options.getInFile());
            }
        }

        LOGGER.info(RES.get("console.createOutPdf", outFile));
        fout = new FileOutputStream(outFile);

        final HashAlgorithm hashAlgorithm = options.getHashAlgorithmX();

        LOGGER.info(RES.get("console.createSignature"));
        char tmpPdfVersion = '\0'; // default version - the same as input
        if (reader.getPdfVersion() < hashAlgorithm.getPdfVersion()) {
            // this covers also problems with visible signatures (embedded
            // fonts) in PDF 1.2, because the minimal version
            // for hash algorithms is 1.3 (for SHA1)
            if (options.isAppendX()) {
                // if we are in append mode and version should be updated
                // then return false (not possible)
                LOGGER.info(RES.get("console.updateVersionNotPossibleInAppendMode"));
                return false;
            }
            tmpPdfVersion = hashAlgorithm.getPdfVersion();
            LOGGER.info(RES.get("console.updateVersion",
                    new String[] { String.valueOf(reader.getPdfVersion()), String.valueOf(tmpPdfVersion) }));
        }

        final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null,
                options.isAppendX());
        if (!options.isAppendX()) {
            // we are not in append mode, let's remove existing signatures
            // (otherwise we're getting to troubles)
            final AcroFields acroFields = stp.getAcroFields();
            @SuppressWarnings("unchecked")
            final List<String> sigNames = acroFields.getSignatureNames();
            for (String sigName : sigNames) {
                acroFields.removeField(sigName);
            }
        }
        if (options.isAdvanced() && options.getPdfEncryption() != PDFEncryption.NONE) {
            LOGGER.info(RES.get("console.setEncryption"));
            final int tmpRight = options.getRightPrinting().getRight()
                    | (options.isRightCopy() ? PdfWriter.ALLOW_COPY : 0)
                    | (options.isRightAssembly() ? PdfWriter.ALLOW_ASSEMBLY : 0)
                    | (options.isRightFillIn() ? PdfWriter.ALLOW_FILL_IN : 0)
                    | (options.isRightScreanReaders() ? PdfWriter.ALLOW_SCREENREADERS : 0)
                    | (options.isRightModifyAnnotations() ? PdfWriter.ALLOW_MODIFY_ANNOTATIONS : 0)
                    | (options.isRightModifyContents() ? PdfWriter.ALLOW_MODIFY_CONTENTS : 0);
            switch (options.getPdfEncryption()) {
            case PASSWORD:
                stp.setEncryption(true, options.getPdfUserPwdStr(), options.getPdfOwnerPwdStrX(), tmpRight);
                break;
            case CERTIFICATE:
                final X509Certificate encCert = KeyStoreUtils
                        .loadCertificate(options.getPdfEncryptionCertFile());
                if (encCert == null) {
                    LOGGER.error(RES.get("console.pdfEncError.wrongCertificateFile",
                            StringUtils.defaultString(options.getPdfEncryptionCertFile())));
                    return false;
                }
                if (!KeyStoreUtils.isEncryptionSupported(encCert)) {
                    LOGGER.error(RES.get("console.pdfEncError.cantUseCertificate",
                            encCert.getSubjectDN().getName()));
                    return false;
                }
                stp.setEncryption(new Certificate[] { encCert }, new int[] { tmpRight },
                        PdfWriter.ENCRYPTION_AES_128);
                break;
            default:
                LOGGER.error(RES.get("console.unsupportedEncryptionType"));
                return false;
            }
        }

        final PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        final String reason = options.getReason();
        if (StringUtils.isNotEmpty(reason)) {
            LOGGER.info(RES.get("console.setReason", reason));
            sap.setReason(reason);
        }
        final String location = options.getLocation();
        if (StringUtils.isNotEmpty(location)) {
            LOGGER.info(RES.get("console.setLocation", location));
            sap.setLocation(location);
        }
        final String contact = options.getContact();
        if (StringUtils.isNotEmpty(contact)) {
            LOGGER.info(RES.get("console.setContact", contact));
            sap.setContact(contact);
        }
        LOGGER.info(RES.get("console.setCertificationLevel"));
        sap.setCertificationLevel(options.getCertLevelX().getLevel());

        if (options.isVisible()) {
            // visible signature is enabled
            LOGGER.info(RES.get("console.configureVisible"));
            LOGGER.info(RES.get("console.setAcro6Layers", Boolean.toString(options.isAcro6Layers())));
            sap.setAcro6Layers(options.isAcro6Layers());

            final String tmpImgPath = options.getImgPath();
            if (tmpImgPath != null) {
                LOGGER.info(RES.get("console.createImage", tmpImgPath));
                final Image img = Image.getInstance(tmpImgPath);
                LOGGER.info(RES.get("console.setSignatureGraphic"));
                sap.setSignatureGraphic(img);
            }
            final String tmpBgImgPath = options.getBgImgPath();
            if (tmpBgImgPath != null) {
                LOGGER.info(RES.get("console.createImage", tmpBgImgPath));
                final Image img = Image.getInstance(tmpBgImgPath);
                LOGGER.info(RES.get("console.setImage"));
                sap.setImage(img);
            }
            LOGGER.info(RES.get("console.setImageScale"));
            sap.setImageScale(options.getBgImgScale());
            LOGGER.info(RES.get("console.setL2Text"));
            final String signer = PdfPKCS7.getSubjectFields((X509Certificate) chain[0]).getField("CN");
            final String timestamp = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z")
                    .format(sap.getSignDate().getTime());
            if (options.getL2Text() != null) {
                final Map<String, String> replacements = new HashMap<String, String>();
                replacements.put(L2TEXT_PLACEHOLDER_SIGNER, StringUtils.defaultString(signer));
                replacements.put(L2TEXT_PLACEHOLDER_TIMESTAMP, timestamp);
                replacements.put(L2TEXT_PLACEHOLDER_LOCATION, StringUtils.defaultString(location));
                replacements.put(L2TEXT_PLACEHOLDER_REASON, StringUtils.defaultString(reason));
                replacements.put(L2TEXT_PLACEHOLDER_CONTACT, StringUtils.defaultString(contact));
                final String l2text = StrSubstitutor.replace(options.getL2Text(), replacements);
                sap.setLayer2Text(l2text);
            } else {
                final StringBuilder buf = new StringBuilder();
                buf.append(RES.get("default.l2text.signedBy")).append(" ").append(signer).append('\n');
                buf.append(RES.get("default.l2text.date")).append(" ").append(timestamp);
                if (StringUtils.isNotEmpty(reason))
                    buf.append('\n').append(RES.get("default.l2text.reason")).append(" ").append(reason);
                if (StringUtils.isNotEmpty(location))
                    buf.append('\n').append(RES.get("default.l2text.location")).append(" ").append(location);
                sap.setLayer2Text(buf.toString());
            }
            if (FontUtils.getL2BaseFont() != null) {
                sap.setLayer2Font(new Font(FontUtils.getL2BaseFont(), options.getL2TextFontSize()));
            }
            LOGGER.info(RES.get("console.setL4Text"));
            sap.setLayer4Text(options.getL4Text());
            LOGGER.info(RES.get("console.setRender"));
            RenderMode renderMode = options.getRenderMode();
            if (renderMode == RenderMode.GRAPHIC_AND_DESCRIPTION && sap.getSignatureGraphic() == null) {
                LOGGER.warn(
                        "Render mode of visible signature is set to GRAPHIC_AND_DESCRIPTION, but no image is loaded. Fallback to DESCRIPTION_ONLY.");
                LOGGER.info(RES.get("console.renderModeFallback"));
                renderMode = RenderMode.DESCRIPTION_ONLY;
            }
            sap.setRender(renderMode.getRender());
            LOGGER.info(RES.get("console.setVisibleSignature"));
            int page = options.getPage();
            if (page < 1 || page > reader.getNumberOfPages()) {
                page = reader.getNumberOfPages();
            }
            sap.setVisibleSignature(new Rectangle(options.getPositionLLX(), options.getPositionLLY(),
                    options.getPositionURX(), options.getPositionURY()), page, null);
        }

        LOGGER.info(RES.get("console.processing"));
        final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
        if (!StringUtils.isEmpty(reason)) {
            dic.setReason(sap.getReason());
        }
        if (!StringUtils.isEmpty(location)) {
            dic.setLocation(sap.getLocation());
        }
        if (!StringUtils.isEmpty(contact)) {
            dic.setContact(sap.getContact());
        }
        dic.setDate(new PdfDate(sap.getSignDate()));
        sap.setCryptoDictionary(dic);

        final Proxy tmpProxy = options.createProxy();

        final CRLInfo crlInfo = new CRLInfo(options, chain);

        // CRLs are stored twice in PDF c.f.
        // PdfPKCS7.getAuthenticatedAttributeBytes
        final int contentEstimated = (int) (Constants.DEFVAL_SIG_SIZE + 2L * crlInfo.getByteCount());
        final Map<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
        exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
        sap.preClose(exc);

        PdfPKCS7 sgn = new PdfPKCS7(key, chain, crlInfo.getCrls(), hashAlgorithm.getAlgorithmName(), null,
                false);
        InputStream data = sap.getRangeStream();
        final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgorithmName());
        byte buf[] = new byte[8192];
        int n;
        while ((n = data.read(buf)) > 0) {
            messageDigest.update(buf, 0, n);
        }
        byte hash[] = messageDigest.digest();
        Calendar cal = Calendar.getInstance();
        byte[] ocsp = null;
        if (options.isOcspEnabledX() && chain.length >= 2) {
            LOGGER.info(RES.get("console.getOCSPURL"));
            String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
            if (StringUtils.isEmpty(url)) {
                // get from options
                LOGGER.info(RES.get("console.noOCSPURL"));
                url = options.getOcspServerUrl();
            }
            if (!StringUtils.isEmpty(url)) {
                LOGGER.info(RES.get("console.readingOCSP", url));
                final OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle((X509Certificate) chain[0],
                        (X509Certificate) chain[1], url);
                ocspClient.setProxy(tmpProxy);
                ocsp = ocspClient.getEncoded();
            }
        }
        byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
        sgn.update(sh, 0, sh.length);

        TSAClientBouncyCastle tsc = null;
        if (options.isTimestampX() && !StringUtils.isEmpty(options.getTsaUrl())) {
            LOGGER.info(RES.get("console.creatingTsaClient"));
            if (options.getTsaServerAuthn() == ServerAuthentication.PASSWORD) {
                tsc = new TSAClientBouncyCastle(options.getTsaUrl(),
                        StringUtils.defaultString(options.getTsaUser()),
                        StringUtils.defaultString(options.getTsaPasswd()));
            } else {
                tsc = new TSAClientBouncyCastle(options.getTsaUrl());

            }
            final String tsaHashAlg = options.getTsaHashAlgWithFallback();
            LOGGER.info(RES.get("console.settingTsaHashAlg", tsaHashAlg));
            tsc.setHashAlgorithm(tsaHashAlg);
            tsc.setProxy(tmpProxy);
            final String policyOid = options.getTsaPolicy();
            if (StringUtils.isNotEmpty(policyOid)) {
                LOGGER.info(RES.get("console.settingTsaPolicy", policyOid));
                tsc.setPolicy(policyOid);
            }
        }
        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);

        if (contentEstimated + 2 < encodedSig.length) {
            System.err.println(
                    "SigSize - contentEstimated=" + contentEstimated + ", sigLen=" + encodedSig.length);
            throw new Exception("Not enough space");
        }

        byte[] paddedSig = new byte[contentEstimated];
        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);

        PdfDictionary dic2 = new PdfDictionary();
        dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
        LOGGER.info(RES.get("console.closeStream"));
        sap.close(dic2);
        fout.close();
        fout = null;
        finished = true;
    } catch (Exception e) {
        LOGGER.error(RES.get("console.exception"), e);
    } catch (OutOfMemoryError e) {
        LOGGER.fatal(RES.get("console.memoryError"), e);
    } finally {
        if (fout != null) {
            try {
                fout.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        LOGGER.info(RES.get("console.finished." + (finished ? "ok" : "error")));
        options.fireSignerFinishedEvent(tmpException);
    }
    return finished;
}

From source file:net.sf.jsignpdf.UncompressPdf.java

License:Mozilla Public License

/**
 * The main 'main'./*from  www .j  a  va2s.  co m*/
 * 
 * @param args
 */
public static void main(String[] args) {
    if (args == null || args.length == 0) {
        System.out.println("Usage:\njava " + UncompressPdf.class.getName() + " file.pdf [file2.pdf [...]]");
        return;
    }
    Document.compress = false;
    for (String tmpFile : args) {
        String newFileName = null;
        if (tmpFile.toLowerCase().endsWith(".pdf")) {
            newFileName = tmpFile.substring(0, tmpFile.length() - 4) + "_uncompressed.pdf";
        } else {
            newFileName = tmpFile + "_uncompressed.pdf";
        }
        System.out.println("Uncompressing " + tmpFile + " to " + newFileName);
        try {
            PdfReader reader = new PdfReader(tmpFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(newFileName), '\0');
            int total = reader.getNumberOfPages() + 1;
            for (int i = 1; i < total; i++) {
                reader.setPageContent(i, reader.getPageContent(i));
            }
            stamper.close();
        } catch (NullPointerException npe) {
            npe.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.sf.sze.service.impl.converter.PdfConverterImpl.java

License:GNU General Public License

/**
 * {@inheritDoc}/*www  .j a v a  2s.  c  o m*/
 */
@Override
public File concatAll(File directory, String praefix) {
    final String completePdfName = praefix + "_complete.pdf";
    final File completePdf = new File(directory, completePdfName);
    completePdf.delete();

    final String[] pdfs = directory.list(new PrefixFileFilter(praefix));
    if ((pdfs != null) && (pdfs.length > 0)) {

        final Document document = new Document();
        try {
            final PdfCopy copy = new PdfCopy(document, new FileOutputStream(completePdf));
            copy.setPDFXConformance(PdfWriter.PDFA1B);
            document.open();
            addPdfAInfosToDictonary(copy);
            Arrays.sort(pdfs);

            for (String pdfName : pdfs) {
                if (completePdfName.equals(pdfName) || pdfName.startsWith(".")) {
                    continue;
                }

                try {
                    final PdfReader reader = new PdfReader(new FileInputStream(new File(directory, pdfName)));
                    for (int page = 1; page <= reader.getNumberOfPages(); page++) {
                        copy.addPage(copy.getImportedPage(reader, page));
                    }
                } catch (DocumentException de) {
                    LOG.error(pdfName, de);
                    throw de;
                } catch (IOException io) {
                    LOG.error(pdfName, io);
                    throw io;
                }
            }
        } catch (DocumentException e) {
            throw new PDFConversionException(e);
        } catch (IOException e) {
            throw new PDFConversionException(e);
        } finally {
            document.close();
        }
    }

    return completePdf;
}

From source file:net.sf.sze.service.impl.converter.PdfConverterImpl.java

License:GNU General Public License

/**
 * {@inheritDoc}//from  www . j a  v a  2 s  . co m
 */
@Override
public int convertOdtToA4(File odtFile, File pdfFileA4, OO2PdfConverter oo2pdfConverter) {
    LOG.debug("Create DinA4-PDF");

    final int result;
    try {
        File tempPdf = File.createTempFile(FilenameUtils.getBaseName(pdfFileA4.getName()), ".pdf");
        FileUtils.deleteQuietly(tempPdf);
        oo2pdfConverter.convert(odtFile, tempPdf);

        PdfReader reader = new PdfReader(new FileInputStream(tempPdf));
        makeCleanPdfA(reader, pdfFileA4);
        FileUtils.deleteQuietly(tempPdf);
        result = reader.getNumberOfPages();
    } catch (DocumentException e) {
        throw new PDFConversionException(e);
    } catch (IOException e) {
        throw new PDFConversionException(e);
    }

    return result;
}