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

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

Introduction

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

Prototype

public boolean isEncrypted() 

Source Link

Document

Returns true if the PDF is encrypted.

Usage

From source file:br.com.nordestefomento.jrimum.utilix.PDFUtil.java

License:Apache License

/**
 * <p>/*from ww  w .jav a2  s  . c om*/
 * Junta varios arquivos pdf em um soh.
 * </p>
 * 
 * @param pdfFiles
 *            Lista de array de bytes
 * 
 * @return Arquivo PDF em forma de byte
 * @since 0.2
 */
@SuppressWarnings("unchecked")
public static byte[] mergeFiles(List<byte[]> pdfFiles) {

    // retorno
    byte[] bytes = null;

    if (isNotNull(pdfFiles) && !pdfFiles.isEmpty()) {

        int pageOffset = 0;
        boolean first = true;

        ArrayList master = null;
        Document document = null;
        PdfCopy writer = null;
        ByteArrayOutputStream byteOS = null;

        try {

            byteOS = new ByteArrayOutputStream();
            master = new ArrayList();

            for (byte[] doc : pdfFiles) {

                if (isNotNull(doc)) {

                    // cria-se um reader para cada documento

                    PdfReader reader = new PdfReader(doc);

                    if (reader.isEncrypted()) {
                        reader = new PdfReader(doc, "".getBytes());
                    }

                    reader.consolidateNamedDestinations();

                    // pega-se o numero total de paginas
                    int n = reader.getNumberOfPages();
                    List bookmarks = SimpleBookmark.getBookmark(reader);

                    if (isNotNull(bookmarks)) {
                        if (pageOffset != 0) {
                            SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                        }
                        master.addAll(bookmarks);
                    }

                    pageOffset += n;

                    if (first) {

                        // passo 1: criar um document-object
                        document = new Document(reader.getPageSizeWithRotation(1));

                        // passo 2: criar um writer que observa o documento
                        writer = new PdfCopy(document, byteOS);
                        document.addAuthor("JRimum Group");
                        document.addSubject("JRimum Merged Document");
                        document.addCreator("JRimum Utilix");

                        // passo 3: abre-se o documento
                        document.open();
                        first = false;
                    }

                    // passo 4: adciona-se o conteudo
                    PdfImportedPage page;
                    for (int i = 0; i < n;) {
                        ++i;
                        page = writer.getImportedPage(reader, i);

                        writer.addPage(page);
                    }
                }
            }

            if (master.size() > 0) {
                writer.setOutlines(master);
            }

            // passo 5: fecha-se o documento
            if (isNotNull(document)) {
                document.close();
            }

            bytes = byteOS.toByteArray();

        } catch (Exception e) {
            LOG.error("", e);
        }
    }

    return bytes;
}

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 . ja va 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.pdfsam.plugin.coverfooter.GUI.CoverFooterMainGUI.java

License:Open Source License

private void addTableRow(File file_to_add) {
    if (file_to_add != null) {
        boolean encrypt = false;
        String num_pages = "";
        try {//  w  w  w. ja v a2s  .  com
            //fix 03/07 for memory usage
            PdfReader pdf_reader = new PdfReader(new RandomAccessFileOrArray(file_to_add.getAbsolutePath()),
                    null);
            encrypt = pdf_reader.isEncrypted();
            // we retrieve the total number of pages
            num_pages = Integer.toString(pdf_reader.getNumberOfPages());
            pdf_reader.close();
        } catch (Exception ex) {
            num_pages = ex.getMessage();
        }
        try {
            modello_cover_table.addRow(new CoverFooterItemType(file_to_add.getName(),
                    file_to_add.getAbsolutePath(), num_pages, CoverFooterMainGUI.ALL_STRING, encrypt));
            fireLogPropertyChanged(
                    GettextResource.gettext(i18n_messages, "File selected: ") + file_to_add.getName(),
                    LogPanel.LOG_INFO);
        } catch (Exception ex) {
            fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error: ") + ex.getMessage(),
                    LogPanel.LOG_ERROR);

        }
    }
}

From source file:it.pdfsam.plugin.coverfooter.GUI.CoverFooterMainGUI.java

License:Open Source License

private void addTableRowsFromNode(Node file_node) {
    if (file_node != null) {
        boolean encrypt = false;
        String num_pages = "";
        String page_selection = "";
        File file_to_add = null;//from www .  j  a  va  2 s .  c o  m
        try {
            Node file_name = (Node) file_node.selectSingleNode("@name");
            if (file_name != null) {
                file_to_add = new File(file_name.getText());
            }
        } catch (Exception ex) {
            file_to_add = null;
            fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error: ") + ex.getMessage(),
                    LogPanel.LOG_ERROR);
        }
        try {
            if (file_to_add != null) {
                PdfReader pdf_reader = new PdfReader(new RandomAccessFileOrArray(file_to_add.getAbsolutePath()),
                        null);
                encrypt = pdf_reader.isEncrypted();
                // we retrieve the total number of pages
                num_pages = Integer.toString(pdf_reader.getNumberOfPages());
                pdf_reader.close();
            }
        } catch (Exception ex) {
            num_pages = ex.getMessage();
        }
        try {
            Node file_pages = (Node) file_node.selectSingleNode("@pageselection");
            if (file_pages != null) {
                page_selection = file_pages.getText();
            } else {
                page_selection = CoverFooterMainGUI.ALL_STRING;
            }
        } catch (Exception ex) {
            page_selection = CoverFooterMainGUI.ALL_STRING;
        }
        try {
            modello_cover_table.addRow(new CoverFooterItemType(file_to_add.getName(),
                    file_to_add.getAbsolutePath(), num_pages, page_selection, encrypt));
            fireLogPropertyChanged(
                    GettextResource.gettext(i18n_messages, "File selected: ") + file_to_add.getName(),
                    LogPanel.LOG_INFO);
        } catch (Exception ex) {
            fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error: ") + ex.getMessage(),
                    LogPanel.LOG_ERROR);

        }
    }
}

From source file:it.pdfsam.plugin.coverfooter.type.TableTransferHandler.java

License:Open Source License

/**
 * Drop the CoverFooterItem// w  w  w . j a va2  s .  com
 */
public boolean importData(JComponent c, Transferable t) {
    if (!(c instanceof JCoverFooterTable)) {
        return false;
    }
    if (canImport(c, t.getTransferDataFlavors())) {
        try {
            if (hasCoverFooterItemFlavor(t)) {
                Object obj = t.getTransferData(CoverFooterItemTransfer.COVERFOOTERITEMFLAVOUR);
                if (!(obj instanceof CoverFooterItemTransfer))
                    return false;
                CoverFooterItemTransfer mit = (CoverFooterItemTransfer) obj;
                ArrayList cover_item_obj = mit.getData();
                importCoverFooterItem(c, cover_item_obj);
                return true;
            } else if (hasFileFlavor(t)) {
                List file_list = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
                ArrayList row_items = new ArrayList();
                for (int i = 0; i < file_list.size(); i++) {
                    File file_item = (File) file_list.get(i);
                    boolean encrypt = false;
                    String num_pages = "";
                    try {
                        PdfReader pdf_reader = new PdfReader(file_item.getAbsolutePath());
                        encrypt = pdf_reader.isEncrypted();
                        // we retrieve the total number of pages
                        num_pages = Integer.toString(pdf_reader.getNumberOfPages());
                    } catch (Exception ex) {
                        num_pages = ex.getMessage();

                    }
                    CoverFooterItemType cover_item_obj = new CoverFooterItemType(file_item.getName(),
                            file_item.getAbsolutePath(), num_pages, "All", encrypt);
                    row_items.add(cover_item_obj);
                }
                importCoverFooterItem(c, row_items);
                return true;
            } else {
                return false;
            }
        } catch (UnsupportedFlavorException ufe) {
        } catch (IOException ioe) {
        }
    }
    return false;
}

From source file:it.pdfsam.plugin.merge.GUI.MergeMainGUI.java

License:Open Source License

private void addTableRow(File file_to_add) {
    if (file_to_add != null) {
        boolean encrypt = false;
        String num_pages = "";
        try {/*from  w w  w .ja  v a 2  s  .  com*/
            //fix 03/07 for memory usage
            PdfReader pdf_reader = new PdfReader(new RandomAccessFileOrArray(file_to_add.getAbsolutePath()),
                    null);
            encrypt = pdf_reader.isEncrypted();
            // we retrieve the total number of pages
            num_pages = Integer.toString(pdf_reader.getNumberOfPages());
            pdf_reader.close();
        } catch (Exception ex) {
            num_pages = ex.getMessage();
        }
        try {
            modello_merge_table.addRow(new MergeItemType(file_to_add.getName(), file_to_add.getAbsolutePath(),
                    num_pages, MergeMainGUI.ALL_STRING, encrypt));
            fireLogPropertyChanged(
                    GettextResource.gettext(i18n_messages, "File selected: ") + file_to_add.getName(),
                    LogPanel.LOG_INFO);
        } catch (Exception ex) {
            fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error: ") + ex.getMessage(),
                    LogPanel.LOG_ERROR);

        }
    }
}

From source file:it.pdfsam.plugin.merge.GUI.MergeMainGUI.java

License:Open Source License

private void addTableRowsFromNode(Node file_node) {
    if (file_node != null) {
        boolean encrypt = false;
        String num_pages = "";
        String page_selection = "";
        File file_to_add = null;/*  w w w.j av a2  s . c  om*/
        try {
            Node file_name = (Node) file_node.selectSingleNode("@name");
            if (file_name != null) {
                file_to_add = new File(file_name.getText());
            }
        } catch (Exception ex) {
            file_to_add = null;
            fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error: ") + ex.getMessage(),
                    LogPanel.LOG_ERROR);
        }
        try {
            if (file_to_add != null) {
                PdfReader pdf_reader = new PdfReader(new RandomAccessFileOrArray(file_to_add.getAbsolutePath()),
                        null);
                encrypt = pdf_reader.isEncrypted();
                // we retrieve the total number of pages
                num_pages = Integer.toString(pdf_reader.getNumberOfPages());
                pdf_reader.close();
            }
        } catch (Exception ex) {
            num_pages = ex.getMessage();
        }
        try {
            Node file_pages = (Node) file_node.selectSingleNode("@pageselection");
            if (file_pages != null) {
                page_selection = file_pages.getText();
            } else {
                page_selection = MergeMainGUI.ALL_STRING;
            }
        } catch (Exception ex) {
            page_selection = MergeMainGUI.ALL_STRING;
        }
        try {
            modello_merge_table.addRow(new MergeItemType(file_to_add.getName(), file_to_add.getAbsolutePath(),
                    num_pages, page_selection, encrypt));
            fireLogPropertyChanged(
                    GettextResource.gettext(i18n_messages, "File selected: ") + file_to_add.getName(),
                    LogPanel.LOG_INFO);
        } catch (Exception ex) {
            fireLogPropertyChanged(GettextResource.gettext(i18n_messages, "Error: ") + ex.getMessage(),
                    LogPanel.LOG_ERROR);

        }
    }
}

From source file:it.pdfsam.plugin.merge.type.TableTransferHandler.java

License:Open Source License

/**
 * Drop the MergeItem//from  w ww .ja v  a  2s. c o m
 */
public boolean importData(JComponent c, Transferable t) {
    if (!(c instanceof JMergeTable)) {
        return false;
    }
    if (canImport(c, t.getTransferDataFlavors())) {
        try {
            if (hasMergeItemFlavor(t)) {
                Object obj = t.getTransferData(MergeItemTransfer.MERGEITEMFLAVOUR);
                if (!(obj instanceof MergeItemTransfer))
                    return false;
                MergeItemTransfer mit = (MergeItemTransfer) obj;
                ArrayList merge_item_obj = mit.getData();
                importMergeItem(c, merge_item_obj);
                return true;
            } else if (hasFileFlavor(t)) {
                List file_list = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
                ArrayList row_items = new ArrayList();
                for (int i = 0; i < file_list.size(); i++) {
                    File file_item = (File) file_list.get(i);
                    boolean encrypt = false;
                    String num_pages = "";
                    try {
                        PdfReader pdf_reader = new PdfReader(file_item.getAbsolutePath());
                        encrypt = pdf_reader.isEncrypted();
                        // we retrieve the total number of pages
                        num_pages = Integer.toString(pdf_reader.getNumberOfPages());
                    } catch (Exception ex) {
                        num_pages = ex.getMessage();

                    }
                    MergeItemType merge_item_obj = new MergeItemType(file_item.getName(),
                            file_item.getAbsolutePath(), num_pages, "All", encrypt);
                    row_items.add(merge_item_obj);
                }
                importMergeItem(c, row_items);
                return true;
            } else {
                return false;
            }
        } catch (UnsupportedFlavorException ufe) {
        } catch (IOException ioe) {
        }
    }
    return false;
}

From source file:lucee.runtime.tag.PDF.java

License:Open Source License

private void doActionThumbnail() throws PageException, IOException, DocumentException {
    required("pdf", "thumbnail", "source", source);

    PDFDocument doc = toPDFDocument(source, password, null);
    PdfReader pr = doc.getPdfReader();
    boolean isEnc = pr.isEncrypted();
    pr.close();/*from w  ww .  ja  v a 2s  .  com*/
    if (isEnc) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //PDFUtil.concat(new PDFDocument[]{doc}, baos, true, true, true, (char)0);
        PDFUtil.encrypt(doc, baos, null, null, 0, PDFUtil.ENCRYPT_NONE);
        baos.close();
        doc = new PDFDocument(baos.toByteArray(), doc.getResource(), null);
    }

    doc.setPages(pages);

    // scale
    if (scale < 1)
        throw new ApplicationException("value of attribute scale [" + scale + "] should be at least 1");

    // destination
    if (destination == null)
        destination = ResourceUtil.toResourceNotExisting(pageContext, "thumbnails");

    // imagePrefix
    if (imagePrefix == null) {
        Resource res = doc.getResource();
        if (res != null) {
            String n = res.getName();
            int index = n.lastIndexOf('.');
            if (index != -1)
                imagePrefix = n.substring(0, index);
            else
                imagePrefix = n;
        } else
            imagePrefix = "memory";
    }

    // MUST password
    PDFUtil.writeImages(doc.getRaw(), doc.getPages(), destination, imagePrefix, format, scale, overwrite,
            resolution == RESOLUTION_HIGH, transparent);

}

From source file:lucee.runtime.text.pdf.PDFDocument.java

License:Open Source License

public Struct getInfo() {

    PdfReader pr = null;
    try {//ww w.j  a va  2  s . c  o  m
        pr = getPdfReader();
        //PdfDictionary catalog = pr.getCatalog();
        int permissions = pr.getPermissions();
        boolean encrypted = pr.isEncrypted();

        Struct info = new StructImpl();
        info.setEL("FilePath", getFilePath());

        // access
        info.setEL("ChangingDocument", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_CONTENTS));
        info.setEL("Commenting", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_ANNOTATIONS));
        info.setEL("ContentExtraction", allowed(encrypted, permissions, PdfWriter.ALLOW_SCREENREADERS));
        info.setEL("CopyContent", allowed(encrypted, permissions, PdfWriter.ALLOW_COPY));
        info.setEL("DocumentAssembly",
                allowed(encrypted, permissions, PdfWriter.ALLOW_ASSEMBLY + PdfWriter.ALLOW_MODIFY_CONTENTS));
        info.setEL("FillingForm",
                allowed(encrypted, permissions, PdfWriter.ALLOW_FILL_IN + PdfWriter.ALLOW_MODIFY_ANNOTATIONS));
        info.setEL("Printing", allowed(encrypted, permissions, PdfWriter.ALLOW_PRINTING));
        info.setEL("Secure", "");
        info.setEL("Signing", allowed(encrypted, permissions, PdfWriter.ALLOW_MODIFY_ANNOTATIONS
                + PdfWriter.ALLOW_MODIFY_CONTENTS + PdfWriter.ALLOW_FILL_IN));

        info.setEL("Encryption", encrypted ? "Password Security" : "No Security");// MUST
        info.setEL("TotalPages", Caster.toDouble(pr.getNumberOfPages()));
        info.setEL("Version", "1." + pr.getPdfVersion());
        info.setEL("permissions", "" + permissions);
        info.setEL("permiss", "" + PdfWriter.ALLOW_FILL_IN);

        info.setEL("Application", "");
        info.setEL("Author", "");
        info.setEL("CenterWindowOnScreen", "");
        info.setEL("Created", "");
        info.setEL("FitToWindow", "");
        info.setEL("HideMenubar", "");
        info.setEL("HideToolbar", "");
        info.setEL("HideWindowUI", "");
        info.setEL("Keywords", "");
        info.setEL("Language", "");
        info.setEL("Modified", "");
        info.setEL("PageLayout", "");
        info.setEL("Producer", "");
        info.setEL("Properties", "");
        info.setEL("ShowDocumentsOption", "");
        info.setEL("ShowWindowsOption", "");
        info.setEL("Subject", "");
        info.setEL("Title", "");
        info.setEL("Trapped", "");

        // info
        HashMap imap = pr.getInfo();
        Iterator it = imap.entrySet().iterator();
        Map.Entry entry;
        while (it.hasNext()) {
            entry = (Entry) it.next();
            info.setEL(Caster.toString(entry.getKey(), null), entry.getValue());
        }
        return info;
    } catch (PageException pe) {
        throw new PageRuntimeException(pe);
    } finally {
        if (pr != null)
            pr.close();
    }
}