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:com.urservices.urerp.ecole.views.PdfReportView.java

@Override
protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter pdfWriter,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {// ww  w.  j  a v  a2  s.com

        PdfReader pdfTemplate = new PdfReader((InputStream) model.get("template"));
        PdfStamper stamper = new PdfStamper(pdfTemplate, response.getOutputStream());
        stamper.setFormFlattening(true);

        stamper.getAcroFields().setField("txtNom", "Kamdoum");
        stamper.getAcroFields().setField("txtPrenom", "Samuel");

        stamper.close();
        pdfTemplate.close();

        System.out.println("This PDF has " + pdfTemplate.getNumberOfPages() + " pages.");

    } catch (Exception e) {
        System.out.println("PdfReportView.buildPdfDocument() " + e.getMessage());
    }
}

From source file:com.userweave.batch.CreatePDF.java

License:Open Source License

public static void main(String[] args) {
    if (args.length == 0) {
        args = new String[] { "one.pdf", "two.pdf", "out.pdf" };
    }//from  w  ww .  j  av  a2s .co  m
    if (args.length == 3) {
        try {
            // the document we're watermarking
            PdfReader document = new PdfReader(args[0]);
            int num_pages = document.getNumberOfPages();

            // the watermark (or letterhead, etc.)
            PdfReader mark = new PdfReader(args[1]);
            Rectangle mark_page_size = mark.getPageSize(1);

            // the output document
            PdfStamper writer = new PdfStamper(document, new FileOutputStream(args[2]));

            // create a PdfTemplate from the first page of mark
            // (PdfImportedPage is derived from PdfTemplate)
            PdfImportedPage mark_page = writer.getImportedPage(mark, 1);

            for (int ii = 0; ii < num_pages;) {
                // iterate over document's pages, adding mark_page as
                // a layer 'underneath' the page content; scale mark_page
                // and move it so it fits within the document's page;
                // if document's page is cropped, then this scale might
                // not be small enough

                ++ii;
                Rectangle doc_page_size = document.getPageSize(ii);
                float h_scale = doc_page_size.getWidth() / mark_page_size.getWidth();
                float v_scale = doc_page_size.getHeight() / mark_page_size.getHeight();
                float mark_scale = (h_scale < v_scale) ? h_scale : v_scale;

                float h_trans = (float) ((doc_page_size.getWidth() - mark_page_size.getWidth() * mark_scale)
                        / 2.0);
                float v_trans = (float) ((doc_page_size.getHeight() - mark_page_size.getHeight() * mark_scale)
                        / 2.0);

                PdfContentByte contentByte = writer.getUnderContent(ii);
                contentByte.addTemplate(mark_page, mark_scale, 0, 0, mark_scale, h_trans, v_trans);
            }

            writer.close();
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    } else { // input error
        System.err.println("arguments: in_document in_watermark out_pdf_fn");
    }

}

From source file:com.userweave.domain.service.pdf.ItextUtils.java

License:Open Source License

public OutputStream createPDF(InputStream generatedPDF, InputStream stampPDF, OutputStream out)
        throws IOException, DocumentException {

    // the document we're watermarking
    PdfReader document = new PdfReader(generatedPDF);
    int num_pages = document.getNumberOfPages();

    // the watermark (or letterhead, etc.)
    PdfReader mark = new PdfReader(stampPDF);
    Rectangle mark_page_size = mark.getPageSize(1);

    // the output document
    PdfStamper writer = new PdfStamper(document, out);

    // create a PdfTemplate from the first page of mark
    // (PdfImportedPage is derived from PdfTemplate)
    PdfImportedPage mark_page = writer.getImportedPage(mark, 1);

    for (int ii = 0; ii < num_pages;) {
        // iterate over document's pages, adding mark_page as
        // a layer 'underneath' the page content; scale mark_page
        // and move it so it fits within the document's page;
        // if document's page is cropped, then this scale might
        // not be small enough

        ++ii;/* ww  w.j  av  a  2 s. c o m*/
        Rectangle doc_page_size = document.getPageSize(ii);
        float h_scale = doc_page_size.getWidth() / mark_page_size.getWidth();
        float v_scale = doc_page_size.getHeight() / mark_page_size.getHeight();
        float mark_scale = (h_scale < v_scale) ? h_scale : v_scale;

        float h_trans = (float) ((doc_page_size.getWidth() - mark_page_size.getWidth() * mark_scale) / 2.0);
        float v_trans = (float) ((doc_page_size.getHeight() - mark_page_size.getHeight() * mark_scale) / 2.0);

        PdfContentByte contentByte = writer.getUnderContent(ii);
        contentByte.addTemplate(mark_page, mark_scale, 0, 0, mark_scale, h_trans, v_trans);
    }

    writer.close();

    return out;

    /*      
                  
                  
                  
                  
              PdfReader reader = new PdfReader(origPDF);
                      
              int n = reader.getNumberOfPages();
                      
              Document document = new Document(reader.getPageSizeWithRotation(1));
              PdfWriter writer = PdfWriter.getInstance(document, outfile);
              writer.setEncryption(PdfWriter.STRENGTH40BITS, "pdf", null,
    PdfWriter.AllowCopy);
              document.open();
              PdfContentByte cb = writer.getDirectContent();
              PdfImportedPage page;
              int rotation;
              int i = 0;
              while (i < n) {
    i++;
    document.setPageSize(reader.getPageSizeWithRotation(i));
    document.newPage();
    page = writer.getImportedPage(reader, i);
    rotation = reader.getPageRotation(i);
    if (rotation == 90 || rotation == 270) {
      cb.addTemplate(page, 0, -1f, 1f, 0, 0,
      reader.getPageSizeWithRotation(i).height());
    } else {
      cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
    }
    System.out.println("Processed page " + i);
              }
              document.close();
            } catch( Exception e) {
              e.printStackTrace();
            }
          */

}

From source file:com.virtusa.akura.student.controller.MessageBoardController.java

License:Open Source License

/**
 * Merge many pdf files into one file.//from  w  w w. j av  a 2 s.  c o  m
 *
 * @param streamOfPDFFiles - a list of inputStreams
 * @param outputStream - an instance of outputStream
 * @param paginate - a boolean
 * @throws AkuraAppException - The exception details that occurred when processing
 */
public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate)
        throws AkuraAppException {

    final int fontSize = 8, leftRightAlignment = 8;
    final int min = 0;
    final int max = 5;
    final int size = 300;
    final int xAxis = -150;
    final int pageHeight = 550;
    final int pageHieghtfromBottom = 16;
    final int pageRecHeight = 580;
    final int recHeightFromBottom = 14;
    Document document = new Document(PageSize.A4);
    try {
        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 output stream
        PdfWriter writer = null;
        BaseFont bf = null;
        try {
            writer = PdfWriter.getInstance(document, outputStream);

            document.open();

            bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        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()) {
                if (currentPageNumber != 2) {
                    document.newPage();
                }
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                if (currentPageNumber == 1) {
                    cb.addTemplate(page, 0, xAxis);
                } else if (currentPageNumber != 2) {
                    cb.addTemplate(page, 0, 0);
                }

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, fontSize);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, " " + AkuraWebConstant.REPORT_GPL, size,
                            max, min);
                    cb.newlineText();
                    cb.endText();

                    if (currentPageNumber != 2) {
                        int pageNo = currentPageNumber;
                        if (currentPageNumber != 1) {
                            pageNo = currentPageNumber - 1;
                        }

                        // write the page number inside a rectangle.
                        cb.fillStroke();
                        cb.rectangle(leftRightAlignment, recHeightFromBottom, pageRecHeight,
                                leftRightAlignment);
                        cb.beginText();
                        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, PAGE + pageNo, pageHeight,
                                pageHieghtfromBottom, 0);
                        cb.endText();
                        cb.stroke();
                    }
                }
            }
            pageOfCurrentReaderPDF = 0;
        }

        outputStream.flush();

        document.close();

        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFCreator.java

License:Apache License

public void createPDF(OutputStream out, List<DocumentPart> metsparts, PDFConfiguration pdfconfig,
        MetadataExtractor inMetadataExtractor, StructureMetadataExtractor inBookmarkExtractor,
        Watermark myWatermark) throws ImageManagerException, FileNotFoundException, IOException,
        PDFManagerException, ImageInterpreterException, URISyntaxException, MetsException {
    PDFManager pdfmanager = null;/*from w  ww . jav a2  s .c  o m*/

    String creator = "";
    String title = "";
    String keywords = "";

    int documentpartcounter = 0;
    LinkedList<METSParser> allMetsParser = new LinkedList<METSParser>();
    HashMap<Integer, UrlImage> allPages = new HashMap<Integer, UrlImage>();
    HashMap<Integer, String> allPageNames = new HashMap<Integer, String>();
    HashMap<Integer, PDFTitlePage> allTitlePages = new HashMap<Integer, PDFTitlePage>();
    List<PDFBookmark> allRootBookmarks = new LinkedList<PDFBookmark>();

    // iterate over all DocumentParts
    for (DocumentPart dp : metsparts) {

        documentpartcounter++;
        String pdfdivid = null;
        Map<Integer, UrlImage> documentpartPages = null;

        if (dp.getType() == DocumentPartType.METS) {
            // read the METS file and handle all the images
            // TODO: Do not invoke the METS Parser direct, use the interface instead
            METSParser metsparser = new METSParser(dp.getUrl(), true);

            // set METSParser configuration
            metsparser.setMetadataextractor(inMetadataExtractor);
            metsparser.setStructureMetadataExtractor(inBookmarkExtractor);
            if (dp.getMetsFileGroup() != null) {
                metsparser.setFilegroupsuseattributevalue(dp.getMetsFileGroup());
            }

            if (dp.getDivid() == null) {
                pdfdivid = metsparser.getUppermostDivIDForPDF();
            } else {
                pdfdivid = dp.getDivid();
            }

            // calculate metadata
            inMetadataExtractor.calculatePDFMetadata(pdfdivid, metsparser);

            String title1 = inMetadataExtractor.getPdftitle();
            String creator1 = inMetadataExtractor.getPdfcreator();
            String keywords1 = inMetadataExtractor.getPdfkeywords();

            if (title1 != null) {
                if (title.equals("")) {
                    title = title1;
                } else {
                    title = title + "; " + title1;
                }
            }

            if (creator1 != null) {
                if (creator.equals("")) {
                    creator = creator1;
                } else {
                    creator = creator + "; " + creator1;
                }
            }

            if (keywords1 != null) {
                if (keywords.equals("")) {
                    keywords = keywords1;
                } else {
                    keywords = keywords + "; " + keywords1;
                }
            }

            LOGGER.debug("Title1: " + title1);
            LOGGER.debug("Creator1: " + creator1);
            LOGGER.debug("Keywords1: " + keywords1);

            metsparser.getAllFilesForRelatedDivs(pdfdivid); // get page

            // names
            Map<Integer, String> myPageNames = metsparser.getPageNames();

            // get list of files and pagenames
            documentpartPages = metsparser.getImageMap();

            if (documentpartPages.isEmpty()) {
                // nothing in here; probably METS file has no pages
                // don't add METS file to list
                LOGGER.error("No page files / page urls available!");
            } else {
                // change page names to make them unique
                // within the PDF, different METSparsers
                // will have same pageName

                for (Integer i : documentpartPages.keySet()) {
                    UrlImage page = documentpartPages.get(i);
                    String pagename = myPageNames.get(i);
                    // calculate new integer
                    int dpc = (documentpartcounter * 1000) + i;

                    LOGGER.debug("adding page " + dpc + " to list");

                    // add to new HashMaps
                    allPages.put(dpc, page);
                    allPageNames.put(dpc, pagename);
                }

                // handle all bookmarks
                // need to change page number as well
                List<PDFBookmark> bookmarks;
                bookmarks = PDFBookmark.convertList(metsparser.getStructureList());
                for (PDFBookmark b : bookmarks) {
                    // change page numbers
                    changeBookmarksPagenumber(b, documentpartcounter);
                    allRootBookmarks.add(b);
                }

                // add METSParser to list
                allMetsParser.add(metsparser);
            }
        } else if (dp.getType() == DocumentPartType.PDF) {
            // handle the PDF part
            PdfReader pdfreader = new PdfReader(dp.getUrl());

            int numberofpages = pdfreader.getNumberOfPages();
            for (Integer i = 1; i < numberofpages + 1; i++) {
                PDFPage pdfpage = new PDFPage();
                pdfpage.setPdfreader(pdfreader);
                pdfpage.setPageNumber(i);

                int dpc = (documentpartcounter * 1000) + (i);
                LOGGER.debug("adding page " + dpc + " to list");

                // add page to allPages
                allPages.put(dpc, pdfpage);

                // adding page labales
                String labels[] = PdfPageLabels.getPageLabels(pdfreader);
                if ((labels != null) && (i < labels.length)) {
                    LOGGER.debug("adding Page label (" + i + "):" + labels[i - 1]);
                    allPageNames.put(dpc, labels[i - 1].substring(0, labels[i - 1].length() - 1));
                }
            }

            // add Bookmarks
            allRootBookmarks = extractBookmarksFromPDF(pdfreader, allRootBookmarks, documentpartcounter);
        }
        // handle the title page of this DocumentPart
        if (dp.getTitlepage() != null) {
            // title page is available
            // set the layout of the content file

            // set structType
            if (inMetadataExtractor.getStructType() != null) {
                dp.getTitlepage().setStructuretype(inMetadataExtractor.getStructType());
            }

            dp.getTitlepage().deleteTitleLines();

            // set Lines
            if (inMetadataExtractor.getPdfTitlepageLine1() != null) {
                PDFTitlePageLine ptl = new PDFTitlePageLine(inMetadataExtractor.getPdfTitlepageLine1());
                ptl.setContent(inMetadataExtractor.getPdfTitlepageLine1());
                ptl.setLinetype(2);
                ptl.setFontsize(14);
                dp.getTitlepage().addPDFTitlePageLine(ptl);
            }

            if (inMetadataExtractor.getPdfTitlepageLine2() != null) {
                PDFTitlePageLine ptl = new PDFTitlePageLine(inMetadataExtractor.getPdfTitlepageLine2());
                ptl.setLinetype(2);
                ptl.setFontsize(10);
                dp.getTitlepage().addPDFTitlePageLine(ptl);
            }

            if (inMetadataExtractor.getPdfTitlepageLine3() != null) {
                PDFTitlePageLine ptl = new PDFTitlePageLine(inMetadataExtractor.getPdfTitlepageLine3());
                ptl.setLinetype(2);
                ptl.setFontsize(10);
                dp.getTitlepage().addPDFTitlePageLine(ptl);
            }

            if (inMetadataExtractor.getPdfTitlepageLine4() != null) {
                PDFTitlePageLine ptl = new PDFTitlePageLine(inMetadataExtractor.getPdfTitlepageLine4());
                ptl.setLinetype(2);
                ptl.setFontsize(10);
                dp.getTitlepage().addPDFTitlePageLine(ptl);
            }

            // get name of the first page
            if (documentpartPages != null) {
                Map<Integer, UrlImage> sortedMap = new TreeMap<Integer, UrlImage>(documentpartPages);
                Iterator<Integer> it2 = sortedMap.keySet().iterator();
                Integer firstpagename = 0;
                // TODO: GDZ: Should this just get the first element? - yes
                // I tried to find a more elegant way but my google didn't work #googleneverlikedme
                while (it2.hasNext()) {
                    firstpagename = it2.next();
                    firstpagename = (documentpartcounter * 1000) + firstpagename;
                    LOGGER.debug("Adding PDFTitlePage at page " + firstpagename);
                    break;
                }
                allTitlePages.put(firstpagename, dp.getTitlepage());
            }
        }
    } // end of while over all document parts

    // setting for PDFManager
    pdfmanager = new PDFManager(allPages);
    pdfmanager.setAlwaysUseRenderedImage(pdfconfig.isPdfDefaultAlwaysUseRenderedImage());
    pdfmanager.setAlwaysCompressToJPEG(pdfconfig.isPdfDefaultAlwaysCompressToJPEG());
    pdfmanager.setPdfa(pdfconfig.isWriteAsPdfA());

    // set pages
    LOGGER.debug(allPages.size() + " pages for PDFManager set");
    pdfmanager.setImageURLs(allPages);
    pdfmanager.setImageNames(allPageNames);
    pdfmanager.setStructureList(allRootBookmarks);
    pdfmanager.setPdftitlepages(allTitlePages);

    // set metadata
    if (!title.equals("")) {
        pdfmanager.setTitle(title);
    }
    if (!creator.equals("")) {
        pdfmanager.setCreator(creator);
        pdfmanager.setAuthor(creator);
    }
    if (!keywords.equals("")) {
        pdfmanager.setKeyword(keywords);
    }

    // set an ICC profile
    if (pdfconfig.getIccinputfilename() != null) {
        ICC_Profile iccprofile = ICC_Profile.getInstance(pdfconfig.getIccinputfilename());
        pdfmanager.setIccprofile(iccprofile);
    }

    pdfmanager.createPDF(out, pdfconfig.getPagesize(), myWatermark);
}

From source file:docx4j.TextSubstitution.java

License:Apache License

private int getPageCount() throws IOException {
    int result;/*ww w.jav a 2s  . c o m*/
    // get the number of pages in the file
    PdfReader reader = new PdfReader(this.filePath);
    result = reader.getNumberOfPages();
    reader.close();
    return result;
}

From source file:docx4j.TextSubstitution.java

License:Apache License

private String addWaterMark() throws IOException, DocumentException {
    String result = null;//from   w w  w. jav  a2s .  c o m
    String newFileName = this.getFolderPath() + "wm" + this.fileName;

    try {
        // try to delete the file if it already exists so that we refresh the watermark
        // if it fails then at least we have the existing version which can be deleted manually
        File target = new File(newFileName);
        if (target.exists()) {
            if (!target.delete()) {
                return "existing";
            }
        }

        // add the watermark
        PdfReader reader = new PdfReader(this.filePath);
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(newFileName));
        Image watermark_image = Image.getInstance(this.getFolderPath() + "doc-watermark.png");
        watermark_image.setAbsolutePosition(5, 5);
        int i = 0;
        PdfContentByte add_watermark;

        // loop the pages adding the watermark
        while (i < reader.getNumberOfPages()) {
            i++;
            add_watermark = stamp.getUnderContent(i);
            add_watermark.addImage(watermark_image);
        }
        stamp.close();
        reader.close();
    } catch (Exception e) {
        result = e.getMessage();
    }
    return result;
}

From source file:es.gob.afirma.signers.pades.PAdESSigner.java

License:Open Source License

@SuppressWarnings("boxing")
static byte[] signPDF(final PrivateKey key, final java.security.cert.Certificate[] certChain,
        final byte[] inPDF, final Properties extraParams, final String algorithm)
        throws IOException, AOException, DocumentException, NoSuchAlgorithmException, CertificateException {

    // *********************************************************************************************************************
    // **************** LECTURA PARAMETROS ADICIONALES *********************************************************************
    // *********************************************************************************************************************

    // Imagen de la rubrica
    final Image rubric = getRubricImage(extraParams.getProperty("signatureRubricImage")); //$NON-NLS-1$

    // Usar hora y fecha del sistema
    final boolean useSystemDateTime = Boolean
            .parseBoolean(extraParams.getProperty("applySystemDate", Boolean.TRUE.toString())); //$NON-NLS-1$

    // Motivo de la firma
    final String reason = extraParams.getProperty("signReason"); //$NON-NLS-1$

    // Nombre del campo de firma preexistente en el PDF a usar
    final String signatureField = extraParams.getProperty("signatureField"); //$NON-NLS-1$

    // Lugar de realizacion de la firma
    final String signatureProductionCity = extraParams.getProperty("signatureProductionCity"); //$NON-NLS-1$

    // Datos de contacto (correo electronico) del firmante
    final String signerContact = extraParams.getProperty("signerContact"); //$NON-NLS-1$

    // Pagina donde situar la firma visible
    int page = LAST_PAGE;
    try {/*  ww w.j  av a2 s  . c  o  m*/
        page = Integer.parseInt(extraParams.getProperty("signaturePage")); //$NON-NLS-1$
    } catch (final Exception e) {
        /* Se deja la pagina tal y como esta */
    }

    // Nombre del subfiltro de firma en el diccionario PDF
    final String signatureSubFilter = extraParams.getProperty("signatureSubFilter"); //$NON-NLS-1$

    // ******************
    // ** Adjuntos ******

    // Contenido a adjuntar (en Base64)
    final String b64Attachment = extraParams.getProperty("attach"); //$NON-NLS-1$

    // Nombre que se pondra al fichero adjunto en el PDF
    final String attachmentFileName = extraParams.getProperty("attachFileName"); //$NON-NLS-1$

    // Descripcion del adjunto
    final String attachmentDescription = extraParams.getProperty("attachDescription"); //$NON-NLS-1$

    // ** Fin Adjuntos **
    // ******************

    // Nivel de certificacion del PDF
    int certificationLevel;
    try {
        certificationLevel = extraParams.getProperty("certificationLevel") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("certificationLevel")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        certificationLevel = UNDEFINED;
    }

    // *****************************
    // **** Texto firma visible ****

    // Texto en capa 4
    final String layer4Text = extraParams.getProperty("layer4Text"); //$NON-NLS-1$

    // Texto en capa 2
    final String layer2Text = extraParams.getProperty("layer2Text"); //$NON-NLS-1$

    // Tipo de letra en capa 2
    int layer2FontFamily;
    try {
        layer2FontFamily = extraParams.getProperty("layer2FontFamily") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontFamily")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontFamily = UNDEFINED;
    }

    // Tamano del tipo de letra en capa 2
    int layer2FontSize;
    try {
        layer2FontSize = extraParams.getProperty("layer2FontSize") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontSize")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontSize = UNDEFINED;
    }

    // Estilo del tipo de letra en capa 2
    int layer2FontStyle;
    try {
        layer2FontStyle = extraParams.getProperty("layer2FontStyle") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontStyle")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontStyle = UNDEFINED;
    }

    // Color del tipo de letra en capa 2
    final String layer2FontColor = extraParams.getProperty("layer2FontColor"); //$NON-NLS-1$

    // ** Fin texto firma visible **
    // *****************************

    // Contrasena del propietario del PDF
    String ownerPassword = extraParams.getProperty("ownerPassword"); //$NON-NLS-1$

    // Contrasena del usuario del PDF
    final String userPassword = extraParams.getProperty("userPassword"); //$NON-NLS-1$

    // *********************************************************************************************************************
    // **************** FIN LECTURA PARAMETROS ADICIONALES *****************************************************************
    // *********************************************************************************************************************

    PdfReader pdfReader;
    try {
        if (ownerPassword != null) {
            pdfReader = new PdfReader(inPDF, ownerPassword.getBytes());
        } else if (userPassword != null) {
            pdfReader = new PdfReader(inPDF, userPassword.getBytes());
        } else {
            pdfReader = new PdfReader(inPDF);
        }
    } catch (final BadPasswordException e) {
        // Comprobamos que el signer esta en modo interactivo, y si no lo
        // esta no pedimos contrasena por dialogo, principalmente para no interrumpir un firmado por lotes
        // desatendido
        if (Boolean.TRUE.toString().equalsIgnoreCase(extraParams.getProperty("headLess"))) { //$NON-NLS-1$
            throw new BadPdfPasswordException(e);
        }
        // La contrasena que nos han proporcionada no es buena o no nos
        // proporcionaron ninguna
        ownerPassword = new String(AOUIFactory.getPassword(
                ownerPassword == null ? PDFMessages.getString("AOPDFSigner.0") //$NON-NLS-1$
                        : PDFMessages.getString("AOPDFSigner.1"), //$NON-NLS-1$
                null));
        try {
            pdfReader = new PdfReader(inPDF, ownerPassword.getBytes());
        } catch (final BadPasswordException e2) {
            throw new BadPdfPasswordException(e2);
        }
    } catch (final IOException e) {
        throw new InvalidPdfException(e);
    }

    if (pdfReader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED
            && !Boolean.parseBoolean(extraParams.getProperty("allowSigningCertifiedPdfs"))) { //$NON-NLS-1$
        // Si no permitimos dialogos graficos o directamente hemos indicado que no permitimos firmar PDF certificados lanzamos
        // una excepcion
        if (Boolean.parseBoolean(extraParams.getProperty("headLess")) //$NON-NLS-1$
                || "false".equalsIgnoreCase(extraParams.getProperty("allowSigningCertifiedPdfs"))) { //$NON-NLS-1$ //$NON-NLS-2$
            throw new PdfIsCertifiedException();
        }
        // En otro caso, perguntamos al usuario
        if (AOUIFactory.NO_OPTION == AOUIFactory.showConfirmDialog(null, PDFMessages.getString("AOPDFSigner.8"), //$NON-NLS-1$
                PDFMessages.getString("AOPDFSigner.9"), //$NON-NLS-1$
                AOUIFactory.YES_NO_OPTION, AOUIFactory.WARNING_MESSAGE)) {
            throw new AOCancelledOperationException(
                    "El usuario no ha permitido la firma de un PDF certificado"); //$NON-NLS-1$
        }
    }

    // Los derechos van firmados por Adobe, y como desde iText se invalidan
    // es mejor quitarlos
    pdfReader.removeUsageRights();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Activar el atributo de "agregar firma" (cuarto parametro del metodo
    // "PdfStamper.createSignature") hace que se cree una nueva revision del
    // documento y evita que las firmas previas queden invalidadas. Sin embargo, este
    // exige que el PDF no incorpore ningun error, asi que lo mantendremos desactivado
    // para la primera firma y activado para las subsiguientes. Un error incorporado
    // en un PDF erroneo puede quedar subsanado en su version firmada, haciendo
    // posible incorporar nuevas firmas agregando revisiones del documento.
    final PdfStamper stp;
    try {
        stp = PdfStamper.createSignature(pdfReader, // PDF de entrada
                baos, // Salida
                '\0', // Mantener version
                null, // No crear temporal
                pdfReader.getAcroFields().getSignatureNames().size() > 0 // Si hay mas firmas, creo una revision
        );
    } catch (final BadPasswordException e) {
        throw new PdfIsPasswordProtectedException(e);
    }

    // Aplicamos todos los atributos de firma
    final PdfSignatureAppearance sap = stp.getSignatureAppearance();
    stp.setFullCompression();
    sap.setAcro6Layers(true);

    // PAdES parte 3 seccion 4.7 - Habilitacion para LTV
    stp.getWriter().addDeveloperExtension(new PdfDeveloperExtension(new PdfName("ESIC"), //$NON-NLS-1$
            PdfWriter.PDF_VERSION_1_7, 1));

    // Adjuntos
    if (b64Attachment != null && attachmentFileName != null) {
        byte[] attachment = null;
        try {
            attachment = Base64.decode(b64Attachment);
        } catch (final IOException e) {
            LOGGER.warning("Se ha indicado un adjunto, pero no estaba en formato Base64, se ignorara : " + e); //$NON-NLS-1$
        }
        if (attachment != null) {
            stp.getWriter().addFileAttachment(attachmentDescription, attachment, null, attachmentFileName);
        }
    }

    // iText antiguo
    sap.setRender(PdfSignatureAppearance.SignatureRenderDescription);
    // En iText nuevo seria "sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION);"

    // Razon de firma
    if (reason != null) {
        sap.setReason(reason);
    }

    // Establecer fecha local del equipo
    if (useSystemDateTime) {
        sap.setSignDate(new GregorianCalendar());
    }

    // Gestion de los cifrados
    if (pdfReader.isEncrypted() && (ownerPassword != null || userPassword != null)) {
        if (Boolean.TRUE.toString().equalsIgnoreCase(extraParams.getProperty("avoidEncryptingSignedPdfs"))) { //$NON-NLS-1$
            LOGGER.info(
                    "Aunque el PDF original estaba encriptado no se encriptara el PDF firmado (se establecio el indicativo 'avoidEncryptingSignedPdfs')" //$NON-NLS-1$
            );
        } else {
            LOGGER.info("El PDF original estaba encriptado, se intentara encriptar tambien el PDF firmado" //$NON-NLS-1$
            );
            try {
                stp.setEncryption(ownerPassword != null ? ownerPassword.getBytes() : null,
                        userPassword != null ? userPassword.getBytes() : null, pdfReader.getPermissions(),
                        pdfReader.getCryptoMode());
            } catch (final DocumentException de) {
                LOGGER.warning("No se ha podido cifrar el PDF destino, se escribira sin contrasena: " + de //$NON-NLS-1$
                );
            }
        }
    }

    // Pagina en donde se imprime la firma
    if (page == LAST_PAGE) {
        page = pdfReader.getNumberOfPages();
    }

    // Posicion de la firma
    final Rectangle signaturePositionOnPage = getSignaturePositionOnPage(extraParams);
    if (signaturePositionOnPage != null && signatureField == null) {
        sap.setVisibleSignature(signaturePositionOnPage, page, null);
    } else if (signatureField != null) {
        sap.setVisibleSignature(signatureField);
    }

    // Localizacion en donde se produce la firma
    if (signatureProductionCity != null) {
        sap.setLocation(signatureProductionCity);
    }

    // Contacto del firmante
    if (signerContact != null) {
        sap.setContact(signerContact);
    }

    // Rubrica de la firma
    if (rubric != null) {
        sap.setImage(rubric);
        sap.setLayer2Text(""); //$NON-NLS-1$
        sap.setLayer4Text(""); //$NON-NLS-1$
    }

    // **************************
    // ** Texto en las capas ****
    // **************************

    // Capa 2
    if (layer2Text != null) {

        sap.setLayer2Text(layer2Text);

        final int layer2FontColorR;
        final int layer2FontColorG;
        final int layer2FontColorB;
        if ("black".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else if ("white".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 255;
            layer2FontColorB = 255;
        } else if ("lightGray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 192;
            layer2FontColorG = 192;
            layer2FontColorB = 192;
        } else if ("gray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 128;
            layer2FontColorG = 128;
            layer2FontColorB = 128;
        } else if ("darkGray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 64;
            layer2FontColorG = 64;
            layer2FontColorB = 64;
        } else if ("red".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else if ("pink".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 175;
            layer2FontColorB = 175;
        } else if (layer2FontColor == null) {
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else {
            LOGGER.warning("No se soporta el color '" + layer2FontColor //$NON-NLS-1$
                    + "' para el texto de la capa 4, se usara negro"); //$NON-NLS-1$
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        }

        com.lowagie.text.Font font;
        try {
            Class<?> colorClass;
            if (Platform.getOS() == OS.ANDROID) {
                colorClass = Class.forName("harmony.java.awt.Color"); //$NON-NLS-1$
            } else {
                colorClass = Class.forName("java.awt.Color"); //$NON-NLS-1$
            }
            final Object color = colorClass.getConstructor(Integer.TYPE, Integer.TYPE, Integer.TYPE)
                    .newInstance(layer2FontColorR, layer2FontColorG, layer2FontColorB);

            font = com.lowagie.text.Font.class
                    .getConstructor(Integer.TYPE, Integer.TYPE, Integer.TYPE, colorClass).newInstance(
                            // Family (COURIER = 0, HELVETICA = 1, TIMES_ROMAN = 2, SYMBOL = 3, ZAPFDINGBATS = 4)
                            layer2FontFamily == UNDEFINED ? COURIER : layer2FontFamily,
                            // Size (DEFAULTSIZE = 12)
                            layer2FontSize == UNDEFINED ? DEFAULT_LAYER_2_FONT_SIZE : layer2FontSize,
                            // Style (NORMAL = 0, BOLD = 1, ITALIC = 2, BOLDITALIC = 3, UNDERLINE = 4, STRIKETHRU = 8)
                            layer2FontStyle == UNDEFINED ? com.lowagie.text.Font.NORMAL : layer2FontStyle,
                            // Color
                            color);

        } catch (Exception e) {
            font = new com.lowagie.text.Font(
                    // Family (COURIER = 0, HELVETICA = 1, TIMES_ROMAN = 2, SYMBOL = 3, ZAPFDINGBATS = 4)
                    layer2FontFamily == UNDEFINED ? COURIER : layer2FontFamily,
                    // Size (DEFAULTSIZE = 12)
                    layer2FontSize == UNDEFINED ? DEFAULT_LAYER_2_FONT_SIZE : layer2FontSize,
                    // Style (NORMAL = 0, BOLD = 1, ITALIC = 2, BOLDITALIC = 3, UNDERLINE = 4, STRIKETHRU = 8)
                    layer2FontStyle == UNDEFINED ? com.lowagie.text.Font.NORMAL : layer2FontStyle,
                    // Color
                    null);
        }
        sap.setLayer2Font(font);
    }

    // Capa 4
    if (layer4Text != null) {
        sap.setLayer4Text(layer4Text);
    }

    // ***************************
    // ** Fin texto en las capas *
    // ***************************

    sap.setCrypto(null, certChain, null, null);

    final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE,
            signatureSubFilter != null && !"".equals(signatureSubFilter) ? new PdfName(signatureSubFilter) //$NON-NLS-1$
                    : PdfName.ADBE_PKCS7_DETACHED);

    // Fecha de firma
    if (sap.getSignDate() != null) {
        dic.setDate(new PdfDate(sap.getSignDate()));
    }

    dic.setName(PdfPKCS7.getSubjectFields((X509Certificate) certChain[0]).getField("CN")); //$NON-NLS-1$
    if (sap.getReason() != null) {
        dic.setReason(sap.getReason());
    }

    // Lugar de la firma
    if (sap.getLocation() != null) {
        dic.setLocation(sap.getLocation());
    }

    // Contacto del firmante
    if (sap.getContact() != null) {
        dic.setContact(sap.getContact());
    }

    sap.setCryptoDictionary(dic);

    // Certificacion del PDF (NOT_CERTIFIED = 0, CERTIFIED_NO_CHANGES_ALLOWED = 1,
    // CERTIFIED_FORM_FILLING = 2, CERTIFIED_FORM_FILLING_AND_ANNOTATIONS = 3)
    if (certificationLevel != -1) {
        sap.setCertificationLevel(certificationLevel);
    }

    // Reservamos el espacio necesario en el PDF para insertar la firma
    final HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
    exc.put(PdfName.CONTENTS, Integer.valueOf(CSIZE * 2 + 2));

    sap.preClose(exc);

    // ********************************************************************************
    // **************** CALCULO DEL SIGNED DATA ***************************************
    // ********************************************************************************

    // La norma PAdES establece que si el algoritmo de huella digital es SHA1 debe usarse SigningCertificateV2, y en cualquier
    // otro caso deberia usarse SigningCertificateV2
    boolean signingCertificateV2;
    if (extraParams.containsKey("signingCertificateV2")) { //$NON-NLS-1$
        signingCertificateV2 = Boolean.parseBoolean(extraParams.getProperty("signingCertificateV2")); //$NON-NLS-1$
    } else {
        signingCertificateV2 = !"SHA1".equals(AOSignConstants.getDigestAlgorithmName(algorithm)); //$NON-NLS-1$
    }

    byte[] completeCAdESSignature = GenCAdESEPESSignedData.generateSignedData(
            new P7ContentSignerParameters(inPDF, algorithm), true, // omitContent
            new AdESPolicy(extraParams), signingCertificateV2, key, certChain,
            MessageDigest.getInstance(AOSignConstants.getDigestAlgorithmName(algorithm))
                    .digest(AOUtil.getDataFromInputStream(sap.getRangeStream())),
            AOSignConstants.getDigestAlgorithmName(algorithm), true, // Modo PAdES
            PDF_OID,
            extraParams.getProperty("contentDescription") != null //$NON-NLS-1$
                    ? extraParams.getProperty("contentDescription") //$NON-NLS-1$
                    : PDF_DESC);

    //***************** SELLO DE TIEMPO ****************
    final String tsa = extraParams.getProperty("tsaURL"); //$NON-NLS-1$
    URI tsaURL;
    if (tsa != null) {
        try {
            tsaURL = new URI(tsa);
        } catch (final Exception e) {
            LOGGER.warning("Se ha indicado una URL de TSA invalida (" + tsa //$NON-NLS-1$
                    + "), no se anadira sello de tiempo: " + e); //$NON-NLS-1$
            tsaURL = null;
        }
        if (tsaURL != null) {
            final String tsaPolicy = extraParams.getProperty("tsaPolicy"); //$NON-NLS-1$
            if (tsaPolicy == null) {
                LOGGER.warning(
                        "Se ha indicado una URL de TSA pero no una politica, no se anadira sello de tiempo"); //$NON-NLS-1$
            } else {
                final String tsaHashAlgorithm = extraParams.getProperty("tsaHashAlgorithm"); //$NON-NLS-1$
                completeCAdESSignature = new CMSTimestamper(
                        !Boolean.FALSE.toString().equalsIgnoreCase(extraParams.getProperty("tsaRequireCert")), //$NON-NLS-1$
                        tsaPolicy, tsaURL, extraParams.getProperty("tsaUsr"), //$NON-NLS-1$
                        extraParams.getProperty("tsaPwd"), //$NON-NLS-1$
                        extraParams.getProperty("tsaExtensionOid") != null //$NON-NLS-1$
                                && extraParams.getProperty("tsaExtensionValueBase64") != null ? //$NON-NLS-1$
                                        new TsaRequestExtension[] { new TsaRequestExtension(
                                                extraParams.getProperty("tsaExtensionOid"), //$NON-NLS-1$
                                                Boolean.getBoolean(extraParams
                                                        .getProperty("tsaExtensionCritical", "false")), //$NON-NLS-1$ //$NON-NLS-2$
                                                Base64.decode(
                                                        extraParams.getProperty("tsaExtensionValueBase64")) //$NON-NLS-1$
                                        ) } : null).addTimestamp(completeCAdESSignature,
                                                AOAlgorithmID.getOID(AOSignConstants.getDigestAlgorithmName(
                                                        tsaHashAlgorithm != null ? tsaHashAlgorithm : "SHA1"))); //$NON-NLS-1$
            }
        }

    }
    //************** FIN SELLO DE TIEMPO ****************

    // ********************************************************************************
    // *************** FIN CALCULO DEL SIGNED DATA ************************************
    // ********************************************************************************

    final byte[] outc = new byte[CSIZE];
    if (outc.length < completeCAdESSignature.length) {
        throw new AOException("La firma generada tiene un tamano (" + completeCAdESSignature.length //$NON-NLS-1$
                + ") mayor que el permitido (" + outc.length + ")" //$NON-NLS-1$ //$NON-NLS-2$
        );
    }
    final PdfDictionary dic2 = new PdfDictionary();
    System.arraycopy(completeCAdESSignature, 0, outc, 0, completeCAdESSignature.length);
    dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));

    sap.close(dic2);

    return baos.toByteArray();
}

From source file:es.gob.afirma.signers.pades.PdfSessionManager.java

License:Open Source License

/** Obtiene los datos PDF relevantes en cuanto a las firmas electr&oacute;nicas, consistentes en los datos
 * a ser firmados con CAdES o PKCS#7 y los metadatos necesarios para su correcta inserci&oacute;n en el PDF.
 * @param inPDF Documento PDF que se desea firmar
 * @param certChain Cadena de certificados del firmante
 * @param signTime Hora de la firma//from  w w  w  .j a v a2  s. c  o  m
 * @param extraParams Par&aacute;metros adicionales de la firma
 * @return Datos PDF relevantes en cuanto a las firmas electr&oacute;nicas
 * @throws AOException En caso de que ocurra cualquier otro tipo de error
 * @throws IOException En caso de errores de entrada / salida
 * @throws DocumentException Si ocurren errores en la estampaci&iacute;n de la firma PDF */
public static PdfTriPhaseSession getSessionData(final byte[] inPDF, final Certificate[] certChain,
        final Calendar signTime, final Properties extraParams)
        throws AOException, IOException, DocumentException {

    // *********************************************************************************************************************
    // **************** LECTURA PARAMETROS ADICIONALES *********************************************************************
    // *********************************************************************************************************************

    // Forzar la creacion de revisiones incluso en PDF no firmados
    final boolean alwaysCreateRevision = Boolean
            .parseBoolean(extraParams.getProperty("alwaysCreateRevision", "true")); //$NON-NLS-1$ //$NON-NLS-2$

    // Imagen de la rubrica
    final Image rubric = PdfPreProcessor.getImage(extraParams.getProperty("signatureRubricImage")); //$NON-NLS-1$

    // Motivo de la firma
    final String reason = extraParams.getProperty("signReason"); //$NON-NLS-1$

    // Nombre del campo de firma preexistente en el PDF a usar
    final String signatureField = extraParams.getProperty("signatureField"); //$NON-NLS-1$

    // Lugar de realizacion de la firma
    final String signatureProductionCity = extraParams.getProperty("signatureProductionCity"); //$NON-NLS-1$

    // Datos de contacto (correo electronico) del firmante
    final String signerContact = extraParams.getProperty("signerContact"); //$NON-NLS-1$

    // Pagina donde situar la firma visible
    int page = LAST_PAGE;
    try {
        page = Integer.parseInt(extraParams.getProperty("signaturePage")); //$NON-NLS-1$
    } catch (final Exception e) {
        /* Se deja la pagina tal y como esta */
    }

    // Nombre del subfiltro de firma en el diccionario PDF
    final String signatureSubFilter = extraParams.getProperty("signatureSubFilter"); //$NON-NLS-1$

    // Nivel de certificacion del PDF
    int certificationLevel;
    try {
        certificationLevel = extraParams.getProperty("certificationLevel") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("certificationLevel")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        certificationLevel = UNDEFINED;
    }

    // *****************************
    // **** Texto firma visible ****

    // Texto en capa 4
    final String layer4Text = extraParams.getProperty("layer4Text"); //$NON-NLS-1$

    // Texto en capa 2
    final String layer2Text = extraParams.getProperty("layer2Text"); //$NON-NLS-1$

    // Tipo de letra en capa 2
    int layer2FontFamily;
    try {
        layer2FontFamily = extraParams.getProperty("layer2FontFamily") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontFamily")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontFamily = UNDEFINED;
    }

    // Tamano del tipo de letra en capa 2
    int layer2FontSize;
    try {
        layer2FontSize = extraParams.getProperty("layer2FontSize") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontSize")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontSize = UNDEFINED;
    }

    // Estilo del tipo de letra en capa 2
    int layer2FontStyle;
    try {
        layer2FontStyle = extraParams.getProperty("layer2FontStyle") != null ? //$NON-NLS-1$
                Integer.parseInt(extraParams.getProperty("layer2FontStyle")) : //$NON-NLS-1$
                -1;
    } catch (final Exception e) {
        layer2FontStyle = UNDEFINED;
    }

    // Color del tipo de letra en capa 2
    final String layer2FontColor = extraParams.getProperty("layer2FontColor"); //$NON-NLS-1$

    // ** Fin texto firma visible **
    // *****************************

    // *********************************************************************************************************************
    // **************** FIN LECTURA PARAMETROS ADICIONALES *****************************************************************
    // *********************************************************************************************************************

    final PdfReader pdfReader = PdfUtil.getPdfReader(inPDF, extraParams,
            Boolean.getBoolean(extraParams.getProperty("headLess")) //$NON-NLS-1$
    );

    //PdfUtil.checkPdfCertification(pdfReader.getCertificationLevel(), extraParams);
    //PdfUtil.checkUnregisteredSignatures(pdfReader, extraParams);

    // Los derechos van firmados por Adobe, y como desde iText se invalidan
    // es mejor quitarlos
    pdfReader.removeUsageRights();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Activar el atributo de "agregar firma" (quinto parametro del metodo
    // "PdfStamper.createSignature") hace que se cree una nueva revision del
    // documento y evita que las firmas previas queden invalidadas.
    // Sin embargo, este procedimiento no funciona cuando los PDF contienen informacion
    // despues de la ultima marca %%EOF, aspecto no permitido en PDF 1.7 (ISO 32000-1:2008)
    // pero si en PDF 1.3 (Adobe) y que se da con frecuencia en PDF generados con bibliotetcas
    // de software libre como QPDF.
    //
    //  Especificacion PDF 1.3
    //   3.4.4, "File Trailer"
    //     Acrobat viewers require only that the %%EOF marker appear somewhere within
    //     the last 1024 bytes of the file.
    //
    //  Especificacion PDF 1.7
    //   7.5.5. File Trailer
    //     The trailer of a PDF file enables a conforming reader to quickly find the
    //     cross-reference table and certain special objects. Conforming readers should read a
    //     PDF file from its end. The last line of the file shall contain only the end-of-file
    //     marker, %%EOF.
    //
    // Para aceptar al menos en algunos casos PDF 1.3 (son aun muy frecuentes, especialmente
    // en archivos, lo mantendremos desactivado para la primera firma y activado para las
    // subsiguientes.
    //
    // No obstante, el integrador puede siempre forzar la creacion de revisiones mediante
    // el parametro "alwaysCreateRevision".
    final PdfStamper stp;
    try {
        stp = PdfStamper.createSignature(
                // PDF de entrada
                pdfReader,
                // Salida
                baos,
                // Mantener version
                '\0',
                // No crear temporal
                null,
                // Si hay mas firmas o asi me lo indican, creo una revision
                alwaysCreateRevision || pdfReader.getAcroFields().getSignatureNames().size() > 0,
                // Momento de la firma
                signTime);
    } catch (final BadPasswordException e) {
        // Comprobamos que el signer esta en modo interactivo, y si no lo
        // esta no pedimos contrasena por dialogo, principalmente para no interrumpir un firmado por lotes
        // desatendido
        if (Boolean.getBoolean(extraParams.getProperty("headLess"))) { //$NON-NLS-1$
            throw new BadPdfPasswordException(e);
        }
        // La contrasena que nos han proporcionada no es buena o no nos
        // proporcionaron ninguna
        final String userPwd = new String(AOUIFactory.getPassword(
                extraParams.getProperty("userPassword") == null ? CommonPdfMessages.getString("AOPDFSigner.0") //$NON-NLS-1$//$NON-NLS-2$
                        : CommonPdfMessages.getString("AOPDFSigner.1"), //$NON-NLS-1$
                null));
        if ("".equals(userPwd)) { //$NON-NLS-1$
            throw new AOCancelledOperationException("Entrada de contrasena de PDF cancelada por el usuario", e //$NON-NLS-1$
            );
        }
        extraParams.put("userPassword", userPwd); //$NON-NLS-1$
        return getSessionData(inPDF, certChain, signTime, extraParams);
    }

    // Aplicamos todos los atributos de firma
    final PdfSignatureAppearance sap = stp.getSignatureAppearance();
    stp.setFullCompression();
    sap.setAcro6Layers(true);

    PdfUtil.enableLtv(stp);

    // Adjuntos
    PdfPreProcessor.attachFile(extraParams, stp);

    // Imagenes
    PdfPreProcessor.addImage(extraParams, stp);

    // Establecemos el render segun iText antiguo, varia en versiones modernas
    sap.setRender(PdfSignatureAppearance.SignatureRenderDescription);

    // Razon de firma
    if (reason != null) {
        sap.setReason(reason);
    }

    sap.setSignDate(signTime);

    // Gestion de los cifrados
    PdfUtil.managePdfEncryption(stp, pdfReader, extraParams);

    // Pagina en donde se imprime la firma
    if (page == LAST_PAGE) {
        page = pdfReader.getNumberOfPages();
    }

    // Posicion de la firma
    final Rectangle signaturePositionOnPage = getSignaturePositionOnPage(extraParams);
    if (signaturePositionOnPage != null && signatureField == null) {
        sap.setVisibleSignature(signaturePositionOnPage, page, null);
    } else if (signatureField != null) {
        sap.setVisibleSignature(signatureField);
    }

    // Localizacion en donde se produce la firma
    if (signatureProductionCity != null) {
        sap.setLocation(signatureProductionCity);
    }

    // Contacto del firmante
    if (signerContact != null) {
        sap.setContact(signerContact);
    }

    // Rubrica de la firma
    if (rubric != null) {
        sap.setImage(rubric);
        sap.setLayer2Text(""); //$NON-NLS-1$
        sap.setLayer4Text(""); //$NON-NLS-1$
    }

    // **************************
    // ** Texto en las capas ****
    // **************************

    // Capa 2
    if (layer2Text != null) {

        sap.setLayer2Text(layer2Text);

        final int layer2FontColorR;
        final int layer2FontColorG;
        final int layer2FontColorB;

        if ("black".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else if ("white".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 255;
            layer2FontColorB = 255;
        } else if ("lightGray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 192;
            layer2FontColorG = 192;
            layer2FontColorB = 192;
        } else if ("gray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 128;
            layer2FontColorG = 128;
            layer2FontColorB = 128;
        } else if ("darkGray".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 64;
            layer2FontColorG = 64;
            layer2FontColorB = 64;
        } else if ("red".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else if ("pink".equalsIgnoreCase(layer2FontColor)) { //$NON-NLS-1$
            layer2FontColorR = 255;
            layer2FontColorG = 175;
            layer2FontColorB = 175;
        } else if (layer2FontColor == null) {
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        } else {
            LOGGER.warning("No se soporta el color '" + layer2FontColor //$NON-NLS-1$
                    + "' para el texto de la capa 4, se usara negro"); //$NON-NLS-1$
            layer2FontColorR = 0;
            layer2FontColorG = 0;
            layer2FontColorB = 0;
        }

        com.lowagie.text.Font font;
        try {
            Class<?> colorClass;
            if (Platform.getOS() == OS.ANDROID) {
                colorClass = Class.forName("harmony.java.awt.Color"); //$NON-NLS-1$
            } else {
                colorClass = Class.forName("java.awt.Color"); //$NON-NLS-1$
            }
            final Object color = colorClass.getConstructor(Integer.TYPE, Integer.TYPE, Integer.TYPE)
                    .newInstance(Integer.valueOf(layer2FontColorR), Integer.valueOf(layer2FontColorG),
                            Integer.valueOf(layer2FontColorB));

            font = com.lowagie.text.Font.class
                    .getConstructor(Integer.TYPE, Float.TYPE, Integer.TYPE, colorClass).newInstance(
                            // Family (COURIER = 0, HELVETICA = 1, TIMES_ROMAN = 2, SYMBOL = 3, ZAPFDINGBATS = 4)
                            Integer.valueOf(layer2FontFamily == UNDEFINED ? COURIER : layer2FontFamily),
                            // Size (DEFAULTSIZE = 12)
                            Float.valueOf(
                                    layer2FontSize == UNDEFINED ? DEFAULT_LAYER_2_FONT_SIZE : layer2FontSize),
                            // Style (NORMAL = 0, BOLD = 1, ITALIC = 2, BOLDITALIC = 3, UNDERLINE = 4, STRIKETHRU = 8)
                            Integer.valueOf(layer2FontStyle == UNDEFINED ? com.lowagie.text.Font.NORMAL
                                    : layer2FontStyle),
                            // Color
                            color);
        } catch (final Exception e) {
            font = new com.lowagie.text.Font(
                    // Family (COURIER = 0, HELVETICA = 1, TIMES_ROMAN = 2, SYMBOL = 3, ZAPFDINGBATS = 4)
                    layer2FontFamily == UNDEFINED ? COURIER : layer2FontFamily,
                    // Size (DEFAULTSIZE = 12)
                    layer2FontSize == UNDEFINED ? DEFAULT_LAYER_2_FONT_SIZE : layer2FontSize,
                    // Style (NORMAL = 0, BOLD = 1, ITALIC = 2, BOLDITALIC = 3, UNDERLINE = 4, STRIKETHRU = 8)
                    layer2FontStyle == UNDEFINED ? com.lowagie.text.Font.NORMAL : layer2FontStyle,
                    // Color
                    null);
        }
        sap.setLayer2Font(font);
    }

    // Capa 4
    if (layer4Text != null) {
        sap.setLayer4Text(layer4Text);
    }

    // ***************************
    // ** Fin texto en las capas *
    // ***************************

    sap.setCrypto(null, certChain, null, null);

    final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE,
            signatureSubFilter != null && !"".equals(signatureSubFilter) ? new PdfName(signatureSubFilter) //$NON-NLS-1$
                    : PdfName.ADBE_PKCS7_DETACHED);

    // Fecha de firma
    if (sap.getSignDate() != null) {
        dic.setDate(new PdfDate(sap.getSignDate()));
    }

    dic.setName(PdfPKCS7.getSubjectFields((X509Certificate) certChain[0]).getField("CN")); //$NON-NLS-1$

    if (sap.getReason() != null) {
        dic.setReason(sap.getReason());
    }

    // Lugar de la firma
    if (sap.getLocation() != null) {
        dic.setLocation(sap.getLocation());
    }

    // Contacto del firmante
    if (sap.getContact() != null) {
        dic.setContact(sap.getContact());
    }

    sap.setCryptoDictionary(dic);

    // Certificacion del PDF (NOT_CERTIFIED = 0, CERTIFIED_NO_CHANGES_ALLOWED = 1,
    // CERTIFIED_FORM_FILLING = 2, CERTIFIED_FORM_FILLING_AND_ANNOTATIONS = 3)
    if (certificationLevel != -1) {
        sap.setCertificationLevel(certificationLevel);
    }

    // Reservamos el espacio necesario en el PDF para insertar la firma
    final HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
    exc.put(PdfName.CONTENTS, Integer.valueOf(CSIZE * 2 + 2));

    sap.preClose(exc, signTime);

    final PdfObject pdfObject = ((com.lowagie.text.pdf.PdfStamperImp) stp.getWriter()).getFileID();

    return new PdfTriPhaseSession(sap, baos, new String(pdfObject.getBytes()));
}

From source file:eu.europa.cedefop.europass.jtool.util.ExtractAttachments.java

License:EUPL

/**
  * Extract the attachment file// w w w . java 2  s.co m
  * @throws Exception
  */
public void execute() throws Exception {
    boolean hasAttachment = false;
    try {
        PdfReader reader = new PdfReader(in);
        PdfDictionary catalog = reader.getCatalog();
        PdfDictionary names = (PdfDictionary) PdfReader.getPdfObject(catalog.get(PdfName.NAMES));
        if (names != null) {
            PdfDictionary embFiles = (PdfDictionary) PdfReader
                    .getPdfObject(names.get(new PdfName("EmbeddedFiles")));
            if (embFiles != null) {
                HashMap embMap = PdfNameTree.readTree(embFiles);
                for (Iterator i = embMap.values().iterator(); i.hasNext();) {
                    PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject((PdfObject) i.next());
                    unpackFile(filespec);
                }
            }
        }
        for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
            PdfArray annots = (PdfArray) PdfReader.getPdfObject(reader.getPageN(k).get(PdfName.ANNOTS));
            if (annots == null)
                continue;
            for (Iterator i = annots.listIterator(); i.hasNext();) {
                PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject((PdfObject) i.next());
                PdfName subType = (PdfName) PdfReader.getPdfObject(annot.get(PdfName.SUBTYPE));
                if (!PdfName.FILEATTACHMENT.equals(subType))
                    continue;
                PdfDictionary filespec = (PdfDictionary) PdfReader.getPdfObject(annot.get(PdfName.FS));
                hasAttachment = true;
                unpackFile(filespec);
            }
        }
    } catch (Exception e) {
        log.error("Error while extracting PDF attachements: " + e);
    }
    if (!hasAttachment)
        throw new Exception("PDF file does not have attachment.");
}