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

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

Introduction

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

Prototype

public PdfReader(PdfReader reader) 

Source Link

Document

Creates an independent duplicate.

Usage

From source file:net.sf.jsignpdf.utils.PdfUtils.java

License:Mozilla Public License

/**
 * It tries to create PDF reader in 3 steps:
 * <ul>//from www . ja  va 2  s .c  om
 * <li>without password</li>
 * <li>with empty password</li>
 * <li>with given password</li>
 * </ul>
 * 
 * @param content
 *          content of PDF
 * @param aPassword
 *          password
 * @return
 * @throws IOException
 */
public static PdfReader getPdfReader(final byte[] content, byte[] aPassword) throws IOException {
    PdfReader tmpReader = null;
    try {
        // try to read without password
        tmpReader = new PdfReader(content);
    } catch (Exception e) {
        try {
            tmpReader = new PdfReader(content, new byte[0]);
        } catch (Exception e2) {
            tmpReader = new PdfReader(content, aPassword);
        }
    }
    return tmpReader;
}

From source file:net.sf.jsignpdf.verify.VerifierLogic.java

License:Mozilla Public License

/**
 * Verifies signature(s) in PDF document.
 * /*from   w ww  . j a  v a 2 s . c o m*/
 * @param tmpReader
 *            PdfReader for given PDF
 * @return
 */
@SuppressWarnings("unchecked")
private VerificationResult verify(final PdfReader tmpReader) {
    final VerificationResult tmpResult = new VerificationResult();
    try {
        final AcroFields tmpAcroFields = tmpReader.getAcroFields();
        final List<String> tmpNames = tmpAcroFields.getSignatureNames();
        tmpResult.setTotalRevisions(tmpAcroFields.getTotalRevisions());

        final int lastSignatureIdx = tmpNames.size() - 1;
        if (lastSignatureIdx < 0) {
            // there is no signature
            tmpResult.setWithoutSignature();
        }
        for (int i = lastSignatureIdx; i >= 0; i--) {
            final String name = tmpNames.get(i);
            final SignatureVerification tmpVerif = new SignatureVerification(name);
            tmpVerif.setLastSignature(i == lastSignatureIdx);
            tmpVerif.setWholeDocument(tmpAcroFields.signatureCoversWholeDocument(name));
            tmpVerif.setRevision(tmpAcroFields.getRevision(name));
            final PdfPKCS7 pk = tmpAcroFields.verifySignature(name);
            final TimeStampToken tst = pk.getTimeStampToken();
            tmpVerif.setTsTokenPresent(tst != null);
            tmpVerif.setTsTokenValidationResult(validateTimeStampToken(tst));
            tmpVerif.setDate(pk.getTimeStampDate() != null ? pk.getTimeStampDate() : pk.getSignDate());
            tmpVerif.setLocation(pk.getLocation());
            tmpVerif.setReason(pk.getReason());
            tmpVerif.setSignName(pk.getSignName());
            final Certificate pkc[] = pk.getCertificates();
            final X509Name tmpX509Name = PdfPKCS7.getSubjectFields(pk.getSigningCertificate());
            tmpVerif.setSubject(tmpX509Name.toString());
            tmpVerif.setModified(!pk.verify());
            tmpVerif.setOcspPresent(pk.getOcsp() != null);
            tmpVerif.setOcspValid(pk.isRevocationValid());
            tmpVerif.setCrlPresent(pk.getCRLs() != null && pk.getCRLs().size() > 0);
            tmpVerif.setFails(PdfPKCS7.verifyCertificates(pkc, kall, pk.getCRLs(), tmpVerif.getDate()));
            tmpVerif.setSigningCertificate(pk.getSigningCertificate());

            // generate CertPath
            List<Certificate> certList = Arrays.asList(pkc);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            CertPath cp = cf.generateCertPath(certList);
            tmpVerif.setCertPath(cp);

            // to save time - check OCSP in certificate only if document's OCSP is not present and valid
            if (!tmpVerif.isOcspValid()) {
                // try to get OCSP url from signing certificate 
                String url = PdfPKCS7.getOCSPURL((X509Certificate) pk.getSigningCertificate());
                tmpVerif.setOcspInCertPresent(url != null);

                if (url != null) {
                    // OCSP url is found in signing certificate - verify certificate with that url
                    tmpVerif.setOcspInCertValid(validateCertificateOCSP(pk.getSignCertificateChain(), url));
                }
            }

            String certificateAlias = kall.getCertificateAlias(pk.getSigningCertificate());
            if (certificateAlias != null) {
                // this means that signing certificate is directly trusted

                String verifyCertificate = PdfPKCS7.verifyCertificate(pk.getSigningCertificate(), pk.getCRLs(),
                        tmpVerif.getDate());
                if (verifyCertificate == null) {
                    // this means that signing certificate is valid
                    tmpVerif.setSignCertTrustedAndValid(true);
                }
            }

            final InputStream revision = tmpAcroFields.extractRevision(name);
            try {
                final PdfReader revisionReader = new PdfReader(revision);
                tmpVerif.setCertLevelCode(revisionReader.getCertificationLevel());
            } finally {
                if (revision != null) {
                    revision.close();
                }
            }
            tmpResult.addVerification(tmpVerif);
            if (failFast && tmpVerif.containsError()) {
                return tmpResult;
            }
        }
    } catch (Exception e) {
        tmpResult.setException(e);
    }
    return tmpResult;
}

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

License:GNU General Public License

/**
 * {@inheritDoc}/*from   ww w. j  a v  a  2s.co  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 w  ww .  j av  a 2s .  c  o 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;
}

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

License:GNU General Public License

/**
 * {@inheritDoc}//from   w  w w  . j  a  v a  2  s .c  o  m
 */
@Override
public void convertA4ToA3(File sourcePdfFileA4, File targetPdfFileA3, File targetPdfFileA4) {
    LOG.debug("Create DinA3-PDF");

    try {
        // we create a reader for a certain document
        PdfReader reader = new PdfReader(new FileInputStream(sourcePdfFileA4));
        // we retrieve the total number of pages
        final int pageNrs = reader.getNumberOfPages();
        switch (pageNrs) {
        case NR_OF_PAGES_1:
            createA4Subdocument(reader, targetPdfFileA4, PAGE_NR_1, EMPTY_PAGE);
            break;
        case NR_OF_PAGES_2:
            createA4Subdocument(reader, targetPdfFileA4, PAGE_NR_1, PAGE_NR_2);
            break;
        case NR_OF_PAGES_3:
            createA3Subdocument(reader, targetPdfFileA3, EMPTY_PAGE, PAGE_NR_1, PAGE_NR_2, PAGE_NR_3);
            break;
        case NR_OF_PAGES_4:
            createA3Subdocument(reader, targetPdfFileA3, PAGE_NR_4, PAGE_NR_1, PAGE_NR_2, PAGE_NR_3);
            break;
        case NR_OF_PAGES_5:
            createA3Subdocument(reader, targetPdfFileA3, EMPTY_PAGE, PAGE_NR_1, PAGE_NR_2, EMPTY_PAGE);
            createA4Subdocument(reader, targetPdfFileA4, PAGE_NR_3, PAGE_NR_4);
            break;
        case NR_OF_PAGES_6:
            createA3Subdocument(reader, targetPdfFileA3, PAGE_NR_6, PAGE_NR_1, PAGE_NR_2, PAGE_NR_5);
            createA4Subdocument(reader, targetPdfFileA4, PAGE_NR_3, PAGE_NR_4);
            break;
        case NR_OF_PAGES_8:
            createA3Subdocument(reader, targetPdfFileA3, PAGE_NR_8, PAGE_NR_1, PAGE_NR_2, PAGE_NR_7, PAGE_NR_6,
                    PAGE_NR_3, PAGE_NR_4, PAGE_NR_5);
            break;
        case NR_OF_PAGES_9:
            createA3Subdocument(reader, targetPdfFileA3, EMPTY_PAGE, PAGE_NR_1, PAGE_NR_2, PAGE_NR_9, PAGE_NR_8,
                    PAGE_NR_3, PAGE_NR_4, PAGE_NR_7);
            createA4Subdocument(reader, targetPdfFileA4, PAGE_NR_5, PAGE_NR_6);
            break;
        case NR_OF_PAGES_10:
            createA3Subdocument(reader, targetPdfFileA3, PAGE_NR_10, PAGE_NR_1, PAGE_NR_2, PAGE_NR_9, PAGE_NR_8,
                    PAGE_NR_3, PAGE_NR_4, PAGE_NR_7);
            createA4Subdocument(reader, targetPdfFileA4, PAGE_NR_5, PAGE_NR_6);
            break;
        default:
            LOG.warn(sourcePdfFileA4.getAbsolutePath() + " has not the right " + "number of pages "
                    + reader.getNumberOfPages() + ".");
        }
    } catch (DocumentException e) {
        throw new PDFConversionException(e);
    } catch (IOException e) {
        throw new PDFConversionException(e);
    }

}

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

License:GNU General Public License

/**
 * Creates an document with an emptyPage.
 * @param pageSize the size of the Page.
 * @return a reader with 1 empty-page.//  w w  w .  j  av  a  2  s. c o m
 */
private synchronized PdfReader getEmptyPDFPage(Rectangle pageSize) {
    if (emptyPdfPage == null) {
        try {
            final int initialByteSize = 1024;
            final ByteArrayOutputStream baos = new ByteArrayOutputStream(initialByteSize);
            final Document emptyDoc = new Document(pageSize);
            final PdfWriter w = PdfWriter.getInstance(emptyDoc, baos);
            emptyDoc.open();
            w.getDirectContent().setLiteral(' ');
            emptyDoc.close();
            this.emptyPdfPage = new PdfReader(baos.toByteArray());
        } catch (Exception e) {
            LOG.error("Can't create an empty-page", e);
        }
    }

    return emptyPdfPage;
}

From source file:net.sourceforge.fenixedu.domain.candidacy.util.GenericApplicationUploadBean.java

License:Open Source License

protected byte[] readStreamContents() throws IOException {
    InputStream stream = this.getStream();
    long fileLength = this.getFileSize();

    if (stream == null || fileLength == 0) {
        return null;
    }//from  www.  ja v a 2s . co  m

    if (fileLength > MAX_FILE_SIZE) {
        throw new DomainException("error.file.to.big");
    }
    byte[] contents = new byte[(int) fileLength];
    stream.read(contents);
    PdfReader pdfFile = new PdfReader(contents);

    return contents;
}

From source file:net.sourceforge.fenixedu.presentationTier.servlets.filters.ProcessCandidacyPrintAllDocumentsFilter.java

License:Open Source License

private ByteArrayOutputStream concatenateDocs(byte[] originalDoc, Person person)
        throws IOException, DocumentException {
    ByteArrayOutputStream concatenatedPdf = new ByteArrayOutputStream();
    PdfCopyFields copy = new PdfCopyFields(concatenatedPdf);

    try {/*w  ww  . j ava2 s. c om*/
        copy.addDocument(new PdfReader(createAcademicAdminProcessSheet(person).toByteArray()));
    } catch (JRException e) {
        logger.error(e.getMessage(), e);
    }
    copy.addDocument(new PdfReader(originalDoc));
    for (PdfFiller pdfFiller : pdfFillersSet) {
        copy.addDocument(new PdfReader(pdfFiller.getFilledPdf(person).toByteArray()));
    }
    copy.close();

    return concatenatedPdf;
}

From source file:net.sourceforge.fenixedu.util.report.ReportsUtils.java

License:Open Source License

static public byte[] stampPdfAt(byte[] originalPdf, byte[] toStampPdf, int positionX, int positionY) {
    try {/*from  w  ww  .j av a  2 s . com*/
        PdfReader originalPdfReader = new PdfReader(originalPdf);
        PdfReader toStampPdfReader = new PdfReader(toStampPdf);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(originalPdfReader, stream);

        PdfImportedPage importedPage = stamper.getImportedPage(toStampPdfReader, 1);

        PdfContentByte overContent = stamper.getOverContent(1);

        Rectangle pageSizeWithRotation = originalPdfReader.getPageSizeWithRotation(1);
        Rectangle pageSizeWithRotationStamper = toStampPdfReader.getPageSizeWithRotation(1);

        logger.info(
                String.format("[ %s, %s]", pageSizeWithRotation.getWidth(), pageSizeWithRotation.getHeight()));
        logger.info(String.format("[ %s, %s]", pageSizeWithRotationStamper.getWidth(),
                pageSizeWithRotationStamper.getHeight()));

        Image image = Image.getInstance(importedPage);

        overContent.addImage(image, image.getWidth(), 0f, 0f, image.getHeight(), positionX, positionY);

        stamper.close();

        originalPdfReader.close();
        toStampPdfReader.close();

        return stream.toByteArray();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:net.sqs2.omr.master.pdfbookmark.PDFtoBookmarkTranslator.java

License:Apache License

@Override
public void execute(InputStream sourceInputStream, String systemId, OutputStream bookmarkOutputStream,
        URIResolver uriResolver) throws InvalidPageMasterException {
    try {//from  ww  w . jav a 2 s.  c  o  m
        PdfReader reader = new PdfReader(sourceInputStream);
        this.numPages = reader.getNumberOfPages();
        SimpleBookmark.exportToXML(SimpleBookmark.getBookmark(reader), bookmarkOutputStream, "UTF-8", false);
        reader.close();
    } catch (IOException ex) {
        throw new InvalidPageMasterException();
    } finally {
    }
}