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(RandomAccessFileOrArray raf, byte ownerPassword[]) throws IOException 

Source Link

Document

Reads and parses a pdf document.

Usage

From source file:com.servoy.extensions.plugins.pdf_output.PDFProvider.java

License:Open Source License

/**
 * Combine multiple protected PDF docs into one.
 * Note: this function may fail when creating large PDF files due to lack of available heap memory. To compensate, please configure the application server with more heap memory via -Xmx parameter.
 *
 * @sample/*from   www  .  j a  v  a  2  s .c om*/
 * pdf_blob_column = combineProtectedPDFDocuments(new Array(pdf_blob1,pdf_blob2,pdf_blob3), new Array(pdf_blob1_pass,pdf_blob2_pass,pdf_blob3_pass));
 *
 * @param pdf_docs_bytearrays  the array of documents to combine
 * @param pdf_docs_passwords an array of passwords to use
 */
public byte[] js_combineProtectedPDFDocuments(Object[] pdf_docs_bytearrays, Object[] pdf_docs_passwords) {
    if (pdf_docs_bytearrays == null || pdf_docs_bytearrays.length == 0)
        return null;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        int pageOffset = 0;
        List master = new ArrayList();
        Document document = null;
        PdfCopy writer = null;
        for (int f = 0; f < pdf_docs_bytearrays.length; f++) {
            if (!(pdf_docs_bytearrays[f] instanceof byte[]))
                continue;
            byte[] pdf_file = (byte[]) pdf_docs_bytearrays[f];

            // we create a reader for a certain document
            byte[] password = null;
            if (pdf_docs_passwords != null && pdf_docs_passwords.length > f && pdf_docs_passwords[f] != null) {
                if (pdf_docs_passwords[f] instanceof String)
                    password = pdf_docs_passwords[f].toString().getBytes();
            }
            PdfReader reader = new PdfReader(pdf_file, password);
            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            List bookmarks = SimpleBookmark.getBookmark(reader);
            if (bookmarks != null) {
                if (pageOffset != 0) {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += n;

            if (writer == null) {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, baos);
                // step 3: we open the document
                document.open();
            }

            // step 4: we add content
            PdfImportedPage page;
            for (int i = 0; i < n;) {
                ++i;
                page = writer.getImportedPage(reader, i);
                writer.addPage(page);
            }
            PRAcroForm form = reader.getAcroForm();
            if (form != null)
                writer.copyAcroForm(reader);
        }
        if (writer != null && document != null) {
            if (master.size() > 0)
                writer.setOutlines(master);
            // step 5: we close the document
            document.close();
        }
        return baos.toByteArray();
    } catch (Throwable e) {
        Debug.error(e);
        throw new RuntimeException("Error combinding pdf documents: " + e.getMessage(), e); //$NON-NLS-1$
    }
}

From source file:com.servoy.extensions.plugins.pdf_output.PDFProvider.java

License:Open Source License

/**
 * Convert a protected PDF form to a PDF document.
 *
 * @sample//from  w w w.  ja v  a2 s .  c o  m
 * var pdfform = plugins.file.readFile('c:/temp/1040a-form.pdf');
 * //var field_values = plugins.file.readFile('c:/temp/1040a-data.fdf');//read adobe fdf values or
 * var field_values = new Array()//construct field values
 * field_values[0] = 'f1-1=John C.J.'
 * field_values[1] = 'f1-2=Longlasting'
 * var result_pdf_doc = plugins.pdf_output.convertProtectedPDFFormToPDFDocument(pdfform, 'pdf_password', field_values)
 * if (result_pdf_doc != null)
 * {
 *    plugins.file.writeFile('c:/temp/1040a-flatten.pdf', result_pdf_doc)
 * }
 *
 * @param pdf_form the PDF Form to convert
 * @param pdf_password the password to use
 * @param field_values the field values to use
 */
public byte[] js_convertProtectedPDFFormToPDFDocument(byte[] pdf_form, String pdf_password,
        Object field_values) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfReader reader = new PdfReader(pdf_form, pdf_password != null ? pdf_password.getBytes() : null);
        PdfStamper stamp = new PdfStamper(reader, baos);
        if (field_values != null) {
            AcroFields form = stamp.getAcroFields();
            if (field_values instanceof String) {
                FdfReader fdf = new FdfReader((String) field_values);
                form.setFields(fdf);
            } else if (field_values instanceof byte[]) {
                FdfReader fdf = new FdfReader((byte[]) field_values);
                form.setFields(fdf);
            } else if (field_values instanceof Object[]) {
                for (int i = 0; i < ((Object[]) field_values).length; i++) {
                    Object obj = ((Object[]) field_values)[i];
                    if (obj instanceof Object[]) {
                        Object[] row = (Object[]) obj;
                        if (row.length >= 2) {
                            Object field = row[0];
                            Object value = row[1];
                            if (field != null && value != null) {
                                form.setField(field.toString(), value.toString());
                            }
                        }
                        //                     else if (row.length >= 3)
                        //                     {
                        //                            form.setField(field, value);
                        //                     }
                    } else if (obj instanceof String) {
                        String s = (String) obj;
                        int idx = s.indexOf('=');
                        form.setField(s.substring(0, idx), s.substring(idx + 1));
                    }
                }
            }
        }
        stamp.setFormFlattening(true);
        stamp.close();
        return baos.toByteArray();
    } catch (Exception e) {
        Debug.error(e);
        throw new RuntimeException("Error converting pdf form to pdf document", e); //$NON-NLS-1$
    }
}

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 {//from w w w . j a  v  a 2  s.  c  om
        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:it.flavianopetrocchi.jpdfbookmarks.itextbookmarksconverter.iTextBookmarksConverter.java

License:Open Source License

@Override
public void open(String pdfPath, byte[] password) throws IOException {
    if (reader != null) {
        close();//  w  w w  .  j ava 2s .c o m
    }
    this.filePath = pdfPath;
    if (password != null) {
        reader = new PdfReader(pdfPath, password);
    } else {
        reader = new PdfReader(pdfPath);
    }
    int preferences = reader.getSimpleViewerPreferences();
    if ((preferences & PdfWriter.PageModeUseOutlines) == 0) {
        showOnOpen = false;
    } else {
        showOnOpen = true;
    }
}

From source file:it.flavianopetrocchi.jpdfbookmarks.itextbookmarksconverter.iTextBookmarksConverter.java

License:Open Source License

public void save(String path, byte[] userPassword, byte[] ownerPassword) throws IOException {
    try {//from  w  w  w  .j  av  a2 s.  co  m
        File tmp = File.createTempFile("jpdf", ".pdf");
        tmp.deleteOnExit();
        Ut.copyFile(this.filePath, tmp.getPath());
        PdfReader tmpReader;
        if (ownerPassword != null) {
            tmpReader = new PdfReader(tmp.getPath(), ownerPassword);
        } else if (userPassword != null) {
            tmpReader = new PdfReader(tmp.getPath(), userPassword);
        } else {
            tmpReader = new PdfReader(tmp.getPath());
        }

        stamper = new PdfStamper(tmpReader, new FileOutputStream(path));
        if (outline != null) {
            stamper.setOutlines(outline);
        }
        int preferences = reader.getSimpleViewerPreferences();
        if (showOnOpen) {
            preferences |= PdfWriter.PageModeUseOutlines;
        } else {
            preferences = preferences & ~PdfWriter.PageModeUseOutlines;
        }
        stamper.setViewerPreferences(preferences);

        if (ownerPassword != null || userPassword != null) {
            //                tmpReader.computeUserPassword();
            if (ownerPassword == null && userPassword != null) {
                ownerPassword = userPassword;
            }
            stamper.setEncryption(userPassword, ownerPassword, tmpReader.getPermissions(),
                    tmpReader.getCryptoMode());
        }
        stamper.close();
        tmp.delete();
    } catch (DocumentException ex) {
    }
}

From source file:it.jugpadova.blo.ParticipantBadgeBo.java

License:Apache License

/**
 * Build a PDF with the badges of confirmed participants.
 */// ww  w . jav  a  2 s  . c o  m
public byte[] buildPDFBadges(Event event) throws IOException, DocumentException {
    List<Participant> participants = participantDao
            .findConfirmedParticipantsByEventIdOrderByLastNameAndFirstName(event.getId());
    int participantsPerPage = getParticipantsPerPage(event);
    int pages = (participants.size() / participantsPerPage) + 2; // prints a more page with empty badges
    ByteArrayOutputStream pdfMergedBaos = new ByteArrayOutputStream();
    PdfCopyFields pdfMerged = new PdfCopyFields(pdfMergedBaos);
    int newIndex = 1;
    for (int i = 0; i < pages; i++) {
        InputStream templateIs = getBadgePageTemplateInputStream(event);
        RandomAccessFileOrArray rafa = new RandomAccessFileOrArray(templateIs);
        PdfReader template = new PdfReader(rafa, null);
        ByteArrayOutputStream pdfPageBaos = new ByteArrayOutputStream();
        PdfStamper pdfPage = new PdfStamper(template, pdfPageBaos);
        AcroFields pdfPageForm = pdfPage.getAcroFields();
        for (int j = 1; j <= participantsPerPage; j++) {
            pdfPageForm.renameField("title" + j, "title" + newIndex);
            pdfPageForm.renameField("firstName" + j, "firstName" + newIndex);
            pdfPageForm.renameField("lastName" + j, "lastName" + newIndex);
            pdfPageForm.renameField("firm" + j, "firm" + newIndex);
            pdfPageForm.renameField("role" + j, "role" + newIndex);
            newIndex++;
        }
        pdfPage.close();
        template.close();
        pdfMerged.addDocument(new PdfReader(pdfPageBaos.toByteArray()));
    }
    pdfMerged.close();
    ByteArrayOutputStream resultBaos = new ByteArrayOutputStream();
    PdfReader mergedReader = new PdfReader(pdfMergedBaos.toByteArray());
    PdfStamper mergedStamper = new PdfStamper(mergedReader, resultBaos);
    AcroFields mergedForm = mergedStamper.getAcroFields();
    int count = 1;
    for (int i = 0; i < pages; i++) {
        for (int j = 1; j <= participantsPerPage; j++) {
            mergedForm.setField("title" + count, event.getTitle());
            count++;
        }
    }
    count = 1;
    for (Participant participant : participants) {
        mergedForm.setField("firstName" + count, participant.getFirstName());
        mergedForm.setField("lastName" + count, participant.getLastName());
        count++;
    }
    mergedStamper.setFormFlattening(true);
    mergedStamper.close();
    return resultBaos.toByteArray();
}

From source file:it.jugpadova.blo.ParticipantBadgeBo.java

License:Apache License

protected int getParticipantsPerPage(Event event) throws IOException {
    int count = 0;
    InputStream templateIs = getBadgePageTemplateInputStream(event);
    RandomAccessFileOrArray rafa = new RandomAccessFileOrArray(templateIs);
    PdfReader template = new PdfReader(rafa, null);
    AcroFields form = template.getAcroFields();
    HashMap fields = form.getFields();
    while (true) {
        if (fields.containsKey("firstName" + (count + 1))) {
            count++;// w  w  w.jav  a  2 s.  c  om
        } else {
            break;
        }
    }
    template.close();
    return count;
}

From source file:it.pdfsam.console.tools.pdf.PdfAlternateMix.java

License:Open Source License

/**
  * Execute the mix command. On error an exception is thrown.
  * @throws AlternateMixException//from   w ww. j av  a  2  s .c  om
  */
public void execute() throws AlternateMixException {
    try {
        workingIndeterminate();
        out_message = "";
        Document pdf_document = null;
        PdfCopy pdf_writer = null;
        File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_file.getParent());
        PdfReader pdf_reader1;
        PdfReader pdf_reader2;

        pdf_reader1 = new PdfReader(new RandomAccessFileOrArray(input_file1.getAbsolutePath()), null);
        pdf_reader1.consolidateNamedDestinations();
        limits1[1] = pdf_reader1.getNumberOfPages();

        pdf_reader2 = new PdfReader(new RandomAccessFileOrArray(input_file2.getAbsolutePath()), null);
        pdf_reader2.consolidateNamedDestinations();
        limits2[1] = pdf_reader2.getNumberOfPages();

        pdf_document = new Document(pdf_reader1.getPageSizeWithRotation(1));
        pdf_writer = new PdfCopy(pdf_document, new FileOutputStream(tmp_o_file));
        if (compressed_boolean) {
            pdf_writer.setFullCompression();
        }
        out_message += LogFormatter.formatMessage("Temporary file created-\n");
        MainConsole.setDocumentCreator(pdf_document);
        pdf_document.open();

        PdfImportedPage page;
        //importo
        boolean finished1 = false;
        boolean finished2 = false;
        int current1 = (reverseFirst) ? limits1[1] : limits1[0];
        int current2 = (reverseSecond) ? limits2[1] : limits2[0];
        while (!finished1 || !finished2) {
            if (!finished1) {
                if (current1 >= limits1[0] && current1 <= limits1[1]) {
                    page = pdf_writer.getImportedPage(pdf_reader1, current1);
                    pdf_writer.addPage(page);
                    current1 = (reverseFirst) ? (current1 - 1) : (current1 + 1);
                } else {
                    out_message += LogFormatter.formatMessage("First file processed-\n");
                    finished1 = true;
                }
            }
            if (!finished2) {
                if (current2 >= limits2[0] && current2 <= limits2[1] && !finished2) {
                    page = pdf_writer.getImportedPage(pdf_reader2, current2);
                    pdf_writer.addPage(page);
                    current2 = (reverseSecond) ? (current2 - 1) : (current2 + 1);
                } else {
                    out_message += LogFormatter.formatMessage("Second file processed-\n");
                    finished2 = true;
                }
            }

        }

        pdf_reader1.close();
        pdf_writer.freeReader(pdf_reader1);
        pdf_reader2.close();
        pdf_writer.freeReader(pdf_reader2);

        pdf_document.close();
        // step 6: temporary buffer moved to output file
        renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean);
        out_message += LogFormatter.formatMessage("Alternate mix completed-\n");

    } catch (Exception e) {
        throw new AlternateMixException(e);
    } finally {
        workCompleted();
    }
}

From source file:it.pdfsam.console.tools.pdf.PdfConcat.java

License:Open Source License

/**
 * Execute the concat command. On error an exception is thrown.
 * @throws ConcatException//from w w w  . ja v  a 2  s .  c o m
 */
public void execute() throws ConcatException {
    try {
        percentageChanged(0, 0);
        out_message = "";
        String file_name;
        int pageOffset = 0;
        ArrayList master = new ArrayList();
        int f = 0;
        Document pdf_document = null;
        PdfConcatenator pdf_writer = null;
        int total_processed_pages = 0;
        String[] page_selection = u_string.split(":");
        File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_file.getParent());
        PdfReader pdf_reader;
        for (Iterator f_list_itr = f_list.iterator(); f_list_itr.hasNext();) {
            String current_p_selection;
            //get page selection. If arrayoutofbounds default behaviour is "all" 
            try {
                current_p_selection = page_selection[f].toLowerCase();
                if (current_p_selection.equals(""))
                    current_p_selection = "all";
            } catch (Exception e) {
                current_p_selection = "all";
            }
            //validation
            if (!(Pattern.compile("([0-9]+[-][0-9]+)|(all)", Pattern.CASE_INSENSITIVE)
                    .matcher(current_p_selection).matches())) {
                String errorMsg = "";
                try {
                    tmp_o_file.delete();
                } catch (Exception e) {
                    errorMsg = " Unable to delete temporary file.";
                }
                throw new ConcatException(
                        "ValidationError: Syntax error on " + current_p_selection + "." + errorMsg);
            }
            file_name = f_list_itr.next().toString();
            //reader creation
            pdf_reader = new PdfReader(new RandomAccessFileOrArray(file_name), null);
            pdf_reader.consolidateNamedDestinations();
            int pdf_number_of_pages = pdf_reader.getNumberOfPages();
            //default behaviour
            int start = 0;
            int end_page = pdf_number_of_pages;
            if (!(current_p_selection.equals("all"))) {
                boolean valid = true;
                String exceptionMsg = "";
                String[] limits = current_p_selection.split("-");
                try {
                    start = Integer.parseInt(limits[0]);
                    end_page = Integer.parseInt(limits[1]);
                } catch (Exception ex) {
                    valid = false;
                    exceptionMsg += "ValidationError: Syntax error on " + current_p_selection + ".";
                    try {
                        tmp_o_file.delete();
                    } catch (Exception e) {
                        exceptionMsg += " Unable to delete temporary file.";
                    }
                }
                if (valid) {
                    //validation
                    if (start < 0) {
                        valid = false;
                        exceptionMsg = "ValidationError: Syntax error. " + (start) + " must be positive in "
                                + current_p_selection + ".";
                        try {
                            tmp_o_file.delete();
                        } catch (Exception e) {
                            exceptionMsg += " Unable to delete temporary file.";
                        }
                    } else if (end_page > pdf_number_of_pages) {
                        valid = false;
                        exceptionMsg = "ValidationError: Cannot merge at page " + end_page + ". No such page.";
                        try {
                            tmp_o_file.delete();
                        } catch (Exception e) {
                            exceptionMsg += " Unable to delete temporary file.";
                        }
                    } else if (start > end_page) {
                        valid = false;
                        exceptionMsg = "ValidationError: Syntax error. " + (start) + " is bigger than "
                                + end_page + " in " + current_p_selection + ".";
                        try {
                            tmp_o_file.delete();
                        } catch (Exception e) {
                            exceptionMsg += " Unable to delete temporary file.";
                        }
                    }
                }
                if (!valid) {
                    throw new ConcatException(exceptionMsg);
                }
            }
            List bookmarks = SimpleBookmark.getBookmark(pdf_reader);
            if (bookmarks != null) {
                //if the end page is not the end of the doc, delete bookmarks after it
                if (end_page < pdf_number_of_pages) {
                    SimpleBookmark.eliminatePages(bookmarks, new int[] { end_page + 1, pdf_number_of_pages });
                }
                // if start page isn't the first page of the document, delete bookmarks before it
                if (start > 0) {
                    SimpleBookmark.eliminatePages(bookmarks, new int[] { 1, start });
                    //bookmarks references must be taken back
                    SimpleBookmark.shiftPageNumbers(bookmarks, -start, null);
                }
                if (pageOffset != 0) {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += (end_page - start);
            out_message += LogFormatter.formatMessage(file_name + ": " + end_page + " pages-\n");
            if (f == 0) {
                if (copyfields_boolean) {
                    // step 1: we create a writer 
                    pdf_writer = new PdfCopyFieldsConcatenator(new FileOutputStream(tmp_o_file),
                            compressed_boolean);
                    HashMap meta = pdf_reader.getInfo();
                    meta.put("Creator", MainConsole.CREATOR);
                } else {
                    // step 1: creation of a document-object
                    pdf_document = new Document(pdf_reader.getPageSizeWithRotation(1));
                    // step 2: we create a writer that listens to the document
                    pdf_writer = new PdfSimpleConcatenator(pdf_document, new FileOutputStream(tmp_o_file),
                            compressed_boolean);
                    // step 3: we open the document
                    MainConsole.setDocumentCreator(pdf_document);
                    pdf_document.open();
                }
                out_message += LogFormatter.formatMessage("Temporary file created-\n");
            }
            // step 4: we add content
            pdf_reader.selectPages(start + "-" + end_page);
            pdf_writer.addDocument(pdf_reader);
            //fix 03/07
            //pdf_reader = null;
            pdf_reader.close();
            pdf_writer.freeReader(pdf_reader);
            total_processed_pages += end_page - start + 1;
            out_message += LogFormatter.formatMessage((end_page - start) + " pages processed correctly-\n");
            f++;
            try {
                percentageChanged((f * 100) / f_list.size(), (end_page - start));
            } catch (RuntimeException re) {
                out_message += LogFormatter.formatMessage("RuntimeException: " + re.getMessage() + "\n");
            }
        }
        if (master.size() > 0) {
            pdf_writer.setOutlines(master);
        }
        out_message += LogFormatter.formatMessage("Total processed pages: " + total_processed_pages + "-\n");
        // step 5: we close the document
        if (pdf_document != null) {
            pdf_document.close();
        }
        pdf_writer.close();
        // step 6: temporary buffer moved to output file
        renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean);
    } catch (Exception e) {
        throw new ConcatException(e);
    } finally {
        workCompleted();
    }
}

From source file:it.pdfsam.console.tools.pdf.PdfEncrypt.java

License:Open Source License

/**
 * Execute the encrypt command. On error an exception is thrown.
 * @throws EncryptException//from ww w .j  av a2  s  .  co m
 */
public void execute() throws EncryptException {
    try {
        workingIndeterminate();
        out_message = "";
        int f = 0;
        for (Iterator f_list_itr = f_list.iterator(); f_list_itr.hasNext();) {
            String file_name = f_list_itr.next().toString();
            prefixParser = new PrefixParser(prefix_value, new File(file_name).getName());
            File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_dir.getAbsolutePath());
            out_message += LogFormatter.formatMessage("Temporary file created-\n");
            PdfReader pdfReader = new PdfReader(new RandomAccessFileOrArray(file_name), null);
            HashMap meta = pdfReader.getInfo();
            meta.put("Creator", MainConsole.CREATOR);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tmp_o_file));
            if (compressed_boolean) {
                pdfStamper.setFullCompression();
            }
            pdfStamper.setMoreInfo(meta);
            pdfStamper.setEncryption(etype, u_pwd, a_pwd, user_permissions);
            pdfStamper.close();
            /*PdfEncryptor.encrypt(pdf_reader,new FileOutputStream(tmp_o_file), etype, u_pwd, a_pwd,user_permissions, meta);*/
            File out_file = new File(o_dir, prefixParser.generateFileName());
            renameTemporaryFile(tmp_o_file, out_file, overwrite_boolean);
            f++;
        }
        out_message += LogFormatter.formatMessage("Pdf files encrypted in " + o_dir.getAbsolutePath() + "-\n"
                + PdfEncryptor.getPermissionsVerbose(user_permissions));
    } catch (Exception e) {
        throw new EncryptException(e);
    } finally {
        workCompleted();
    }
}