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:dk.dma.epd.common.util.FALPDFGenerator.java

License:Apache License

public void generateFal1Form(FALForm1 fal1form, String filename) {

    try {/*www. j  a  v  a  2 s.  co m*/

        PdfReader pdfReader = new PdfReader("FALForm1.pdf");

        FileOutputStream fileWriteStream = new FileOutputStream(filename);

        PdfStamper pdfStamper = new PdfStamper(pdfReader, fileWriteStream);

        for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {

            PdfContentByte content = pdfStamper.getUnderContent(i);

            // Text over the existing page
            BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.WINANSI, BaseFont.EMBEDDED);
            content.beginText();
            content.setFontAndSize(bf, 8);

            int xFirstColum = 68;
            int xSecondColum = 314;

            int startYFirstColumn = 659;

            int startYSecondColumn = 659;

            // Arrival Depature
            if (fal1form.isArrival()) {
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, "X", 316, 690, 0);
            } else {
                // Departure
                content.showTextAligned(PdfContentByte.ALIGN_LEFT, "X", 380, 690, 0);
            }

            // Name and Type of ship
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNameAndTypeOfShip(), xFirstColum,
                    startYFirstColumn, 0);

            // IMO Number
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getImoNumber(), xSecondColum,
                    startYSecondColumn, 0);

            // Call Sign
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getCallSign(), xFirstColum,
                    startYFirstColumn - 30, 0);

            // Voyage Number
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getVoyageNumber(), xSecondColum,
                    startYSecondColumn - 30, 0);

            // Port of Arrival/depature
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getPortOfArrivalDeapture(), xFirstColum,
                    startYFirstColumn - 60, 0);

            // Date and time of arrival/depature
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getDateAndTimeOfArrivalDepature(),
                    xSecondColum, startYFirstColumn - 60, 0);

            // Flag State of ship
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getFlagStateOfShip(), xFirstColum,
                    startYFirstColumn - 90, 0);

            // Name of Master
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNameOfMaster(), xFirstColum + 135,
                    startYFirstColumn - 90, 0);

            // Last port of call/next port of all
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getLastPortOfCall(), xSecondColum,
                    startYFirstColumn - 90, 0);

            // Certificate of registry
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getCertificateOfRegistry(), xFirstColum,
                    startYFirstColumn - 120, 0);

            String nameAndContact = fal1form.getNameAndContactDetalsOfShipsAgent();

            addMultiLine(nameAndContact, startYFirstColumn, xSecondColum, content, 54, 120);

            // Gross Tonnage
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getGrossTonnage(), xFirstColum,
                    startYFirstColumn - 150, 0);

            // Net Tonnage
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNetTonnage(), xFirstColum + 135,
                    startYFirstColumn - 150, 0);

            // Position of the ship in the port
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getPositionOfTheShip(), xFirstColum,
                    startYFirstColumn - 180, 0);

            // Brief particulars of voyage
            String briefVoyageParticulars = fal1form.getBriefParticulars();

            addMultiLine(briefVoyageParticulars, startYFirstColumn, xFirstColum, content, 140, 210);

            // Brief particulars of cargo
            String briefCargoParticulars = fal1form.getBriefDescriptionOfCargo();

            addMultiLine(briefCargoParticulars, startYFirstColumn, xFirstColum, content, 140, 257);

            // Number of Crew
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNumberOfCrew(), xFirstColum,
                    startYFirstColumn - 305, 0);

            // Number of Passengers
            content.showTextAligned(PdfContentByte.ALIGN_LEFT, fal1form.getNumberOfPassengers(),
                    xFirstColum + 130, startYFirstColumn - 305, 0);

            // Remarks
            String remarks = fal1form.getRemarks();
            addMultiLine(remarks, startYFirstColumn, xSecondColum, content, 54, 305);

            // Ship waste requirements
            String wasteRequirements = fal1form.getShipWasteRequirements();
            addMultiLine(wasteRequirements, startYFirstColumn, xSecondColum, content, 54, 405);

            content.endText();
        }

        pdfStamper.close();
        fileWriteStream.close();
        fileWriteStream.flush();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }

}

From source file:ec.rubrica.pdf.FirmadorPdf.java

License:Open Source License

public byte[] firmar(PrivateKey pk, X509Certificate certificado, String razon, String ubicacion)
        throws IOException {
    try {/*from  w w  w.  j a  va  2  s. c om*/
        // Creating the reader and the stamper
        PdfReader reader = new PdfReader(pdf);

        ByteArrayOutputStream signedPdf = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, signedPdf, '\0');

        // Creating the appearance
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setReason(razon);
        appearance.setLocation(ubicacion);

        Rectangle pageSize = reader.getPageSize(1);
        Rectangle position = new Rectangle(15, pageSize.getHeight() - 50, 250, pageSize.getHeight());
        appearance.setVisibleSignature(position, 1, "sig");

        // Creating the signature
        ExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA1, null);

        Certificate[] chain = new Certificate[] { certificado };

        MakeSignature.signDetached(appearance, pks, chain, null, null, tsaClient,
                BouncyCastleProvider.PROVIDER_NAME, 0, MakeSignature.CMS);

        return signedPdf.toByteArray();
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:ec.rubrica.pdf.FirmaPDF.java

License:Open Source License

public static byte[] firmar(byte[] pdf, PrivateKey pk, Certificate[] chain, TSAClient tsaClient)
        throws IOException {
    try {/*from   ww w  .jav  a 2  s .  c o m*/
        // Creating the reader and the stamper
        PdfReader reader = new PdfReader(pdf);
        ByteArrayOutputStream signedPdf = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, signedPdf, '\0');

        // Creating the appearance
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setReason("Testing");
        appearance.setLocation("Quito");
        appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");

        // Creating the signature
        PrivateKeySignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA1, null);

        OcspClient ocsp = new OcspClientBouncyCastle();

        MakeSignature.signDetached(appearance, pks, chain, null, ocsp, tsaClient,
                BouncyCastleProvider.PROVIDER_NAME, 0, MakeSignature.CMS);

        return signedPdf.toByteArray();
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:ec.rubrica.pdf.FirmaPDF.java

License:Open Source License

/**
 * TODO: Mas de dos firmas?/*from  w  w  w  .j  a v  a 2  s .  c om*/
 * 
 * @param pdf
 * @throws IOException
 * @throws SignatureException
 */
public static boolean verificar(byte[] pdf) throws IOException, SignatureException {

    PdfReader reader = new PdfReader(pdf);
    AcroFields af = reader.getAcroFields();
    ArrayList<String> names = af.getSignatureNames();

    for (int k = 0; k < names.size(); ++k) {
        String name = (String) names.get(k);
        System.out.println("Signature name: " + name);
        System.out.println("Signature covers whole document: " + af.signatureCoversWholeDocument(name));
        System.out.println("Document revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());

        PdfPKCS7 pk = af.verifySignature(name);
        Calendar cal = pk.getSignDate();
        Certificate[] pkc = pk.getCertificates();
        TimeStampToken ts = pk.getTimeStampToken();

        if (ts != null) {
            cal = pk.getTimeStampDate();
        }

        if (!pk.isTsp() && ts != null) {
            boolean impr;
            try {
                impr = pk.verifyTimestampImprint();
                System.out.println("Timestamp imprint verifies: " + impr);
                System.out.println("Timestamp date: " + cal);
            } catch (NoSuchAlgorithmException e) {
                throw new SignatureException(e);
            }
        }

        System.out.println("Subject: " + CertificateInfo.getSubjectFields(pk.getSigningCertificate()));
        System.out.println("Document modified: " + !pk.verify());

        KeyStore kall = KeyStoreUtil.loadCacertsKeyStore();

        Object fails[] = CertificateVerification.verifyCertificates(pkc, kall, null, cal);

        if (fails == null) {
            System.out.println("Certificates verified against the KeyStore");
        } else {
            System.out.println("Certificate failed: " + fails[0]);
            return false;
        }

        BasicOCSPResp ocsp = pk.getOcsp();

        if (ocsp != null) {
            try {
                X509Certificate cert = new SecurityDataSubCaCert();

                boolean verifies = ocsp.isSignatureValid(new JcaContentVerifierProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(cert.getPublicKey()));

                System.out.println("OCSP signature verifies: " + verifies);

                System.out.println("OCSP revocation refers to this certificate: " + pk.isRevocationValid());

                return verifies;
            } catch (OperatorCreationException e) {
                throw new SignatureException(e);
            } catch (OCSPException e) {
                throw new SignatureException(e);
            }
        } else {
            return true;
        }
    }

    return false;
}

From source file:ec.rubrica.pdf.PDFUtils.java

License:Open Source License

public static boolean yaEstaFirmado(byte[] archivoPDF) {
    try {/*from   www  .  j a va  2  s.c o  m*/
        // Verificar si ya esta firmado?
        PdfReader reader = new PdfReader(archivoPDF);
        AcroFields fields = reader.getAcroFields();
        ArrayList<String> nombreLista = fields.getSignatureNames();
        for (String nombre : nombreLista) {
            System.out.println("Firmante=" + nombre);
        }
        return (nombreLista.size() == 1);
    } catch (IOException e) {
        throw new RuntimeException(e); // FIXME
    }
}

From source file:ec.rubrica.pdf.VerificadorFirmaPdf.java

License:Open Source License

public VerificadorFirmaPdf(byte[] pdf) throws IOException {
    PdfReader pdfReader = new PdfReader(pdf);
    this.af = pdfReader.getAcroFields();
    this.cacerts = KeyStoreUtil.loadCacertsKeyStore();
}

From source file:edu.clemson.lph.civet.CVIFileController.java

License:Open Source License

/**
 * From the current pdfDecoder, extract the page(s) in aPagesInCurrent to a new pdfData buffer as output stream.
 * @param aPages int[]//from  w w w.  ja v a2 s  .  c om
 * @return byte[]
 */
public byte[] extractPagesToNewPDF() {
    ByteArrayOutputStream baOut = new ByteArrayOutputStream();
    try {
        byte[] pdfDataIn = rawPdfBytes;
        PdfReader reader = new PdfReader(pdfDataIn);
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();
        PdfCopy writer = new PdfCopy(document, baOut);
        document.open();
        for (Integer iPage : aPagesInCurrent) {
            PdfImportedPage pip = writer.getImportedPage(reader, iPage.intValue());
            writer.addPage(pip);
        }
        document.close();
    } catch (IOException ioe) {
        logger.info("IO error extracting pages to byte array", ioe);
        return rawPdfBytes;
    } catch (DocumentException de) {
        logger.info(de.getMessage() + "\nDocument error extracting pages to byte array");
        return rawPdfBytes;
    }
    return baOut.toByteArray();
}

From source file:edu.clemson.lph.pdfgen.MergePDF.java

License:Open Source License

public static void concatPDFs(List<InputStream> pdfInputStreams, OutputStream outputStream, boolean paginate) {
    Document document = new Document();
    try {//  w  ww  . j  a  v a  2 s  . com
        PdfCopy cp = new PdfCopy(document, outputStream);
        document.open();
        Iterator<InputStream> iteratorPDFReader = pdfInputStreams.iterator();

        // Loop through the PDF streams and add to the output.
        while (iteratorPDFReader.hasNext()) {
            InputStream is = iteratorPDFReader.next();
            PdfReader pdfReader = new PdfReader(is);
            int n = pdfReader.getNumberOfPages();
            for (int pageNo = 0; pageNo < n;) {
                pdfReader.getPageN(pageNo);
                cp.addPage(cp.getImportedPage(pdfReader, ++pageNo));
            }
        }
        document.close();
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        logger.error(e);
    }
}

From source file:edu.clemson.lph.pdfgen.PDFUtils.java

License:Open Source License

/**
 * Given an array of bytes from a PDF determine whether at least the first page can be extracted
 * by iText;/*ww  w  .j a  va 2  s  .  co  m*/
 * @param byte[] data to test parse
 * @return byte[]
 */
public static boolean canExtractPages(byte[] pdfDataIn) {
    boolean bRet = false;
    ByteArrayOutputStream baOut = new ByteArrayOutputStream();
    try {
        PdfReader reader = new PdfReader(pdfDataIn);
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();
        PdfCopy writer = new PdfCopy(document, baOut);
        document.open();
        PdfImportedPage pip = writer.getImportedPage(reader, 1);
        writer.addPage(pip);
        document.close();
        byte[] pdfDataOut = baOut.toByteArray();
        int iLen = pdfDataOut.length;
        if (iLen > 0)
            bRet = true;
    } catch (IOException ioe) {
        logger.error(ioe.getMessage() + "\nIO error extracting pages to byte array\n");
        bRet = false;
    } catch (DocumentException de) {
        logger.error(de.getMessage() + "\nDocument error extracting pages to byte array");
        bRet = false;
    }
    return bRet;
}

From source file:edu.clemson.lph.pdfgen.PDFUtils.java

License:Open Source License

/**
 * Use iText 5.x to determine whether a PDF contains an XFA form.
 * @param pdfDataIn//from   w w w. j  ava  2  s  .c o m
 * @return
 */
public static boolean isXFA(byte[] pdfDataIn) {
    boolean bRet = false;
    PdfReader reader;
    try {
        reader = new PdfReader(pdfDataIn);
        XfaForm form = new XfaForm(reader);
        bRet = form.isXfaPresent();
    } catch (IOException e) {
        logger.error(e);
        bRet = false;
    } catch (ParserConfigurationException e) {
        logger.error(e);
        bRet = false;
    } catch (SAXException e) {
        logger.error(e);
        bRet = false;
    }
    return bRet;
}