Example usage for com.lowagie.text.pdf PdfDictionary put

List of usage examples for com.lowagie.text.pdf PdfDictionary put

Introduction

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

Prototype

public void put(PdfName key, PdfObject object) 

Source Link

Document

Associates the specified PdfObject as value with the specified PdfName as key in this map.

Usage

From source file:org.opensignature.opensignpdf.PDFSigner.java

License:Open Source License

/**
 * //from   www. j a  v  a2  s  .  com
 * @param pdfFile
 * @return
 * @throws IOException
 * @throws DocumentException
 * @throws FileNotFoundException
 */
private PdfReader createPDFReader(File pdfFile) throws IOException, DocumentException, FileNotFoundException {

    logger.info("[createPDFReader.in]:: " + Arrays.asList(new Object[] { pdfFile }));

    PdfReader reader;

    if ("true".equals(openOfficeSelected)) {
        String fileName = pdfFile.getPath();
        String tempFileName = fileName + ".temp";
        PdfReader documentPDF = new PdfReader(fileName);

        PdfStamperOSP stamperTemp = new PdfStamperOSP(documentPDF, new FileOutputStream(tempFileName));
        AcroFields af = stamperTemp.getAcroFields();
        af.setGenerateAppearances(true);
        PdfDictionary acro = (PdfDictionary) PdfReader
                .getPdfObject(documentPDF.getCatalog().get(PdfName.ACROFORM));
        acro.remove(PdfName.DR);
        HashMap fields = af.getFields();
        String key;
        for (Iterator it = fields.keySet().iterator(); it.hasNext();) {
            key = (String) it.next();
            int a = af.getFieldType(key);
            if (a == 4) {
                ArrayList widgets = af.getFieldItem(key).widgets;
                PdfDictionary widget = (PdfDictionary) widgets.get(0);
                widget.put(PdfName.FT, new PdfName("Sig"));
                widget.remove(PdfName.V);
                widget.remove(PdfName.DV);
                widget.remove(PdfName.TU);
                widget.remove(PdfName.FF);
                widget.remove(PdfName.DA);
                widget.remove(PdfName.DR);
                widget.remove(PdfName.AP);
            }
        }

        stamperTemp.close();
        documentPDF.close();
        reader = new PdfReader(pdfFile.getPath() + ".temp");

    } else {
        reader = new PdfReader(pdfFile.getPath());

    }

    logger.info("[createPDFReader.retorna]:: ");
    return reader;

}

From source file:org.pdfsam.console.business.pdf.handlers.ConcatCmdExecutor.java

License:Open Source License

/**
 * Apply pages rotations//from ww  w. j av a2  s .com
 * 
 * @param inputFile
 * @param inputCommand
 * @return temporary file with pages rotation
 */
private File applyRotations(File inputFile, ConcatParsedCommand inputCommand) throws Exception {

    rotationReader = new PdfReader(inputFile.getAbsolutePath());
    rotationReader.removeUnusedObjects();
    rotationReader.consolidateNamedDestinations();

    int pdfNumberOfPages = rotationReader.getNumberOfPages();
    PageRotation[] rotations = inputCommand.getRotations();
    if (rotations != null && rotations.length > 0) {
        if (rotations.length > 1) {
            for (int i = 0; i < rotations.length; i++) {
                if (pdfNumberOfPages >= rotations[i].getPageNumber() && rotations[i].getPageNumber() > 0) {
                    PdfDictionary dictionary = rotationReader.getPageN(rotations[i].getPageNumber());
                    int rotation = (rotations[i].getDegrees()
                            + rotationReader.getPageRotation(rotations[i].getPageNumber())) % 360;
                    dictionary.put(PdfName.ROTATE, new PdfNumber(rotation));
                } else {
                    LOG.warn("Rotation for page " + rotations[i].getPageNumber() + " ignored.");
                }
            }
        } else {
            // rotate all
            if (rotations[0].getType() == PageRotation.ALL_PAGES) {
                int pageRotation = rotations[0].getDegrees();
                for (int i = 1; i <= pdfNumberOfPages; i++) {
                    PdfDictionary dictionary = rotationReader.getPageN(i);
                    int rotation = (pageRotation + rotationReader.getPageRotation(i)) % 360;
                    dictionary.put(PdfName.ROTATE, new PdfNumber(rotation));
                }
            } else if (rotations[0].getType() == PageRotation.SINGLE_PAGE) {
                // single page rotation
                if (pdfNumberOfPages >= rotations[0].getPageNumber() && rotations[0].getPageNumber() > 0) {
                    PdfDictionary dictionary = rotationReader.getPageN(rotations[0].getPageNumber());
                    int rotation = (rotations[0].getDegrees()
                            + rotationReader.getPageRotation(rotations[0].getPageNumber())) % 360;
                    dictionary.put(PdfName.ROTATE, new PdfNumber(rotation));
                } else {
                    LOG.warn("Rotation for page " + rotations[0].getPageNumber() + " ignored.");
                }
            } else if (rotations[0].getType() == PageRotation.ODD_PAGES) {
                // odd pages rotation
                int pageRotation = rotations[0].getDegrees();
                for (int i = 1; i <= pdfNumberOfPages; i = i + 2) {
                    PdfDictionary dictionary = rotationReader.getPageN(i);
                    int rotation = (pageRotation + rotationReader.getPageRotation(i)) % 360;
                    dictionary.put(PdfName.ROTATE, new PdfNumber(rotation));
                }
            } else if (rotations[0].getType() == PageRotation.EVEN_PAGES) {
                // even pages rotation
                int pageRotation = rotations[0].getDegrees();
                for (int i = 2; i <= pdfNumberOfPages; i = i + 2) {
                    PdfDictionary dictionary = rotationReader.getPageN(i);
                    int rotation = (pageRotation + rotationReader.getPageRotation(i)) % 360;
                    dictionary.put(PdfName.ROTATE, new PdfNumber(rotation));
                }
            } else {
                LOG.warn("Unable to find the rotation type. " + rotations[0]);
            }
        }
        LOG.info("Pages rotation applied.");
    }
    File rotatedTmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());

    Character pdfVersion = inputCommand.getOutputPdfVersion();

    if (pdfVersion != null) {
        rotationStamper = new PdfStamper(rotationReader, new FileOutputStream(rotatedTmpFile),
                inputCommand.getOutputPdfVersion().charValue());
    } else {
        rotationStamper = new PdfStamper(rotationReader, new FileOutputStream(rotatedTmpFile),
                rotationReader.getPdfVersion());
    }

    HashMap meta = rotationReader.getInfo();
    meta.put("Creator", ConsoleServicesFacade.CREATOR);

    setCompressionSettingOnStamper(inputCommand, rotationStamper);

    rotationStamper.setMoreInfo(meta);
    rotationStamper.close();
    rotationReader.close();
    return rotatedTmpFile;

}

From source file:org.pdfsam.console.business.pdf.handlers.RotateCmdExecutor.java

License:Open Source License

public void execute(AbstractParsedCommand parsedCommand) throws ConsoleException {

    if ((parsedCommand != null) && (parsedCommand instanceof RotateParsedCommand)) {

        RotateParsedCommand inputCommand = (RotateParsedCommand) parsedCommand;
        setPercentageOfWorkDone(0);//from  w  ww.java 2  s . c o  m
        PrefixParser prefixParser;

        try {
            PdfFile[] fileList = inputCommand.getInputFileList();
            for (int i = 0; i < fileList.length; i++) {
                try {

                    prefixParser = new PrefixParser(inputCommand.getOutputFilesPrefix(),
                            fileList[i].getFile().getName());
                    File tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
                    LOG.debug("Opening " + fileList[i].getFile().getAbsolutePath());
                    pdfReader = PdfUtility.fullReaderFor(fileList[i]);
                    pdfReader.removeUnusedObjects();
                    pdfReader.consolidateNamedDestinations();

                    int pdfNumberOfPages = pdfReader.getNumberOfPages();
                    PageRotation rotation = inputCommand.getRotation();
                    // rotate all
                    if (rotation.getType() == PageRotation.ALL_PAGES) {
                        int pageRotation = rotation.getDegrees();
                        LOG.debug("Applying rotation of " + pageRotation + " for all pages");
                        for (int j = 1; j <= pdfNumberOfPages; j++) {
                            PdfDictionary dictionary = pdfReader.getPageN(j);
                            int rotationDegrees = (pageRotation + pdfReader.getPageRotation(j)) % 360;
                            dictionary.put(PdfName.ROTATE, new PdfNumber(rotationDegrees));
                        }
                    } else if (rotation.getType() == PageRotation.ODD_PAGES) {
                        // odd pages rotation
                        int pageRotation = rotation.getDegrees();
                        LOG.debug("Applying rotation of " + pageRotation + " for odd pages");
                        for (int j = 1; j <= pdfNumberOfPages; j = j + 2) {
                            PdfDictionary dictionary = pdfReader.getPageN(j);
                            int rotationDegrees = (pageRotation + pdfReader.getPageRotation(j)) % 360;
                            dictionary.put(PdfName.ROTATE, new PdfNumber(rotationDegrees));
                        }
                    } else if (rotation.getType() == PageRotation.EVEN_PAGES) {
                        // even pages rotation
                        int pageRotation = rotation.getDegrees();
                        LOG.debug("Applying rotation of " + pageRotation + " for even pages");
                        for (int j = 2; j <= pdfNumberOfPages; j = j + 2) {
                            PdfDictionary dictionary = pdfReader.getPageN(j);
                            int rotationDegrees = (pageRotation + pdfReader.getPageRotation(j)) % 360;
                            dictionary.put(PdfName.ROTATE, new PdfNumber(rotationDegrees));
                        }
                    } else {
                        LOG.warn("Unable to find the rotation type. " + rotation);
                    }

                    // version
                    LOG.debug("Creating a new document.");
                    Character pdfVersion = inputCommand.getOutputPdfVersion();
                    if (pdfVersion != null) {
                        pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tmpFile),
                                inputCommand.getOutputPdfVersion().charValue());
                    } else {
                        pdfStamper = new PdfStamper(pdfReader, new FileOutputStream(tmpFile),
                                pdfReader.getPdfVersion());
                    }

                    HashMap meta = pdfReader.getInfo();
                    meta.put("Creator", ConsoleServicesFacade.CREATOR);

                    setCompressionSettingOnStamper(inputCommand, pdfStamper);

                    pdfStamper.setMoreInfo(meta);
                    pdfStamper.close();
                    pdfReader.close();
                    File outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName());
                    FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
                    LOG.debug("Rotated file " + outFile.getCanonicalPath() + " created.");
                    setPercentageOfWorkDone(((i + 1) * WorkDoneDataModel.MAX_PERGENTAGE) / fileList.length);
                } catch (Exception e) {
                    LOG.error("Error rotating file " + fileList[i].getFile().getName(), e);
                }
            }
            LOG.info("Pdf files rotated in " + inputCommand.getOutputFile().getAbsolutePath() + ".");
        } catch (Exception e) {
            throw new EncryptException(e);
        } finally {
            setWorkCompleted();
        }
    } else {
        throw new ConsoleException(ConsoleException.ERR_BAD_COMMAND);
    }
}

From source file:org.sejda.impl.itext.component.PdfRotator.java

License:Apache License

/**
 * apply the rotation to the given page if necessary
 * /* w  w  w  .  j  av  a2s  .  com*/
 * @param pageNmber
 */
private void apply(int pageNmber) {
    if (pages.contains(pageNmber)) {
        PdfDictionary dictionary = reader.getPageN(pageNmber);
        dictionary.put(PdfName.ROTATE, new PdfNumber(
                rotation.addRotation(getRotation(reader.getPageRotation(pageNmber))).getDegrees()));
    }
}

From source file:org.sejda.impl.itext.CropTask.java

License:Apache License

public void execute(CropParameters parameters) throws TaskException {
    PdfSource<?> source = parameters.getSource();
    LOG.debug("Opening {} ", source);
    reader = source.open(sourceOpener);//from w w w .  j  a va 2  s  .  c  om
    int totalPages = reader.getNumberOfPages();

    File tmpFile = createTemporaryPdfBuffer();
    LOG.debug("Created output temporary buffer {} ", tmpFile);

    copier = new DefaultPdfCopier(reader, tmpFile, parameters.getVersion());
    copier.setCompression(parameters.isCompress());

    Set<PdfRectangle> cropAreas = getPdfRectangles(parameters.getCropAreas());
    for (int page = 1; page <= totalPages; page++) {
        PdfDictionary dictionary = reader.getPageN(page);
        for (PdfRectangle cropBox : cropAreas) {
            LOG.trace("Applying crop box {} to page {}", cropBox, page);
            dictionary.put(PdfName.MEDIABOX, cropBox);
            dictionary.put(PdfName.CROPBOX, cropBox);
            copier.addPage(reader, page);
        }
        notifyEvent(getNotifiableTaskMetadata()).stepsCompleted(page).outOf(totalPages);
    }
    nullSafeCloseQuietly(copier);
    nullSafeClosePdfReader(reader);

    outputWriter.setOutput(file(tmpFile).name(parameters.getOutputName()));
    parameters.getOutput().accept(outputWriter);
    LOG.debug("Crop areas applied to {}", parameters.getOutput());
}

From source file:org.signserver.module.pdfsigner.PDFSigner.java

License:Open Source License

protected byte[] addSignatureToPDFDocument(final ICryptoInstance crypto, PDFSignerParameters params,
        byte[] pdfbytes, byte[] password, int contentEstimated, final ProcessRequest request,
        final RequestContext context) throws IOException, DocumentException, CryptoTokenOfflineException,
        SignServerException, IllegalRequestException {
    // when given a content length (i.e. non-zero), it means we are running a second try
    boolean secondTry = contentEstimated != 0;

    // get signing cert certificate chain and private key
    final List<Certificate> certs = getSigningCertificateChain(crypto);
    if (certs == null) {
        throw new SignServerException("Null certificate chain. This signer needs a certificate.");
    }//from   w  ww .j a v  a2 s. c o  m
    final List<Certificate> includedCerts = includedCertificates(certs);
    Certificate[] certChain = includedCerts.toArray(new Certificate[includedCerts.size()]);
    PrivateKey privKey = crypto.getPrivateKey();

    // need to check digest algorithms for DSA private key at signing
    // time since we can't be sure what key a configured alias selector gives back
    if (privKey instanceof DSAPrivateKey) {
        if (!"SHA1".equals(digestAlgorithm)) {
            throw new IllegalRequestException(
                    "Only SHA1 is permitted as digest algorithm for DSA private keys");
        }
    }

    PdfReader reader = new PdfReader(pdfbytes, password);
    boolean appendMode = true; // TODO: This could be good to have as a property in the future

    int pdfVersion;

    try {
        pdfVersion = Integer.parseInt(Character.toString(reader.getPdfVersion()));
    } catch (NumberFormatException e) {
        pdfVersion = 0;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("PDF version: " + pdfVersion);
    }

    // Don't certify already certified documents
    if (reader.getCertificationLevel() != PdfSignatureAppearance.NOT_CERTIFIED
            && params.getCertification_level() != PdfSignatureAppearance.NOT_CERTIFIED) {
        throw new IllegalRequestException("Will not certify an already certified document");
    }

    // Don't sign documents where the certification does not allow it
    if (reader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED
            || reader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_FORM_FILLING) {
        throw new IllegalRequestException("Will not sign a certified document where signing is not allowed");
    }

    Permissions currentPermissions = Permissions.fromInt(reader.getPermissions());

    if (params.getSetPermissions() != null && params.getRemovePermissions() != null) {
        throw new SignServerException("Signer " + workerId + " missconfigured. Only one of " + SET_PERMISSIONS
                + " and " + REMOVE_PERMISSIONS + " should be specified.");
    }

    Permissions newPermissions;
    if (params.getSetPermissions() != null) {
        newPermissions = params.getSetPermissions();
    } else if (params.getRemovePermissions() != null) {
        newPermissions = currentPermissions.withRemoved(params.getRemovePermissions());
    } else {
        newPermissions = null;
    }

    Permissions rejectPermissions = Permissions.fromSet(params.getRejectPermissions());
    byte[] userPassword = reader.computeUserPassword();
    int cryptoMode = reader.getCryptoMode();
    if (LOG.isDebugEnabled()) {
        StringBuilder buff = new StringBuilder();
        buff.append("Current permissions: ").append(currentPermissions).append("\n")
                .append("Remove permissions: ").append(params.getRemovePermissions()).append("\n")
                .append("Reject permissions: ").append(rejectPermissions).append("\n")
                .append("New permissions: ").append(newPermissions).append("\n").append("userPassword: ")
                .append(userPassword == null ? "null" : "yes").append("\n").append("ownerPassword: ")
                .append(password == null ? "no" : (isUserPassword(reader, password) ? "no" : "yes"))
                .append("\n").append("setOwnerPassword: ")
                .append(params.getSetOwnerPassword() == null ? "no" : "yes").append("\n").append("cryptoMode: ")
                .append(cryptoMode);
        LOG.debug(buff.toString());
    }

    if (appendMode && (newPermissions != null || params.getSetOwnerPassword() != null)) {
        appendMode = false;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Changing appendMode to false to be able to change permissions");
        }
    }

    ByteArrayOutputStream fout = new ByteArrayOutputStream();

    // increase PDF version if needed by digest algorithm
    final char updatedPdfVersion;
    if (minimumPdfVersion > pdfVersion) {
        updatedPdfVersion = Character.forDigit(minimumPdfVersion, 10);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Need to upgrade PDF to version 1." + updatedPdfVersion);
        }

        // check that the document isn't already signed 
        // when trying to upgrade version
        final AcroFields af = reader.getAcroFields();
        final List<String> sigNames = af.getSignatureNames();

        if (!sigNames.isEmpty()) {
            // TODO: in the future we might want to support
            // a fallback option in this case to allow re-signing using the same version (using append)
            throw new IllegalRequestException(
                    "Can not upgrade an already signed PDF and a higher version is required to support the configured digest algorithm");
        }

        appendMode = false;
    } else {
        updatedPdfVersion = '\0';
    }

    PdfStamper stp = PdfStamper.createSignature(reader, fout, updatedPdfVersion, null, appendMode);
    PdfSignatureAppearance sap = stp.getSignatureAppearance();

    // Set the new permissions
    if (newPermissions != null || params.getSetOwnerPassword() != null) {
        if (cryptoMode < 0) {
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting default encryption algorithm");
            }
        }
        if (newPermissions == null) {
            newPermissions = currentPermissions;
        }
        if (params.getSetOwnerPassword() != null) {
            password = params.getSetOwnerPassword().getBytes("ISO-8859-1");
        } else if (isUserPassword(reader, password)) {
            // We do not have an owner password so lets use a random one
            password = new byte[16];
            random.nextBytes(password);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting random owner password");
            }
        }
        stp.setEncryption(userPassword, password, newPermissions.asInt(), cryptoMode);
        currentPermissions = newPermissions;
    }

    // Reject if any permissions are rejected and the document does not use a permission password
    // or if it contains any of the rejected permissions
    if (rejectPermissions.asInt() != 0) {
        if (cryptoMode < 0 || currentPermissions.containsAnyOf(rejectPermissions)) {
            throw new IllegalRequestException("Document contains permissions not allowed by this signer");
        }
    }

    // include signer certificate crl inside cms package if requested
    CRL[] crlList = null;
    if (params.isEmbed_crl()) {
        crlList = getCrlsForChain(certs);
    }
    sap.setCrypto(null, certChain, crlList, PdfSignatureAppearance.SELF_SIGNED);

    // add visible signature if requested
    if (params.isAdd_visible_signature()) {
        int signaturePage = getPageNumberForSignature(reader, params);
        sap.setVisibleSignature(new com.lowagie.text.Rectangle(params.getVisible_sig_rectangle_llx(),
                params.getVisible_sig_rectangle_lly(), params.getVisible_sig_rectangle_urx(),
                params.getVisible_sig_rectangle_ury()), signaturePage, null);

        // set custom image if requested
        if (params.isUse_custom_image()) {
            sap.setAcro6Layers(true);
            PdfTemplate n2 = sap.getLayer(2);
            params.getCustom_image().setAbsolutePosition(0, 0);
            n2.addImage(params.getCustom_image());
        }
    }

    // Certification level
    sap.setCertificationLevel(params.getCertification_level());

    PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
    dic.setReason(params.getReason());
    dic.setLocation(params.getLocation());
    dic.setDate(new PdfDate(Calendar.getInstance()));

    sap.setCryptoDictionary(dic);

    // add timestamp to signature if requested
    TSAClient tsc = null;
    if (params.isUse_timestamp()) {
        final String tsaUrl = params.getTsa_url();

        if (tsaUrl != null) {
            tsc = getTimeStampClient(params.getTsa_url(), params.getTsa_username(), params.getTsa_password());
        } else {
            tsc = new InternalTSAClient(getWorkerSession(), params.getTsa_worker(), params.getTsa_username(),
                    params.getTsa_password());
        }
    }

    // embed ocsp response in cms package if requested
    // for ocsp request to be formed there needs to be issuer certificate in
    // chain
    byte[] ocsp = null;
    if (params.isEmbed_ocsp_response() && certChain.length >= 2) {
        String url;
        try {
            url = PdfPKCS7.getOCSPURL((X509Certificate) certChain[0]);
            if (url != null && url.length() > 0) {
                ocsp = new OcspClientBouncyCastle((X509Certificate) certChain[0],
                        (X509Certificate) certChain[1], url).getEncoded();
            }
        } catch (CertificateParsingException e) {
            throw new SignServerException("Error getting OCSP URL from certificate", e);
        }

    }

    PdfPKCS7 sgn;
    try {
        sgn = new PdfPKCS7(privKey, certChain, crlList, digestAlgorithm, null, false);
    } catch (InvalidKeyException e) {
        throw new SignServerException("Error constructing PKCS7 package", e);
    } catch (NoSuchProviderException e) {
        throw new SignServerException("Error constructing PKCS7 package", e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignServerException("Error constructing PKCS7 package", e);
    }

    MessageDigest messageDigest;
    try {
        messageDigest = MessageDigest.getInstance(digestAlgorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new SignServerException("Error creating " + digestAlgorithm + " digest", e);
    }

    Calendar cal = Calendar.getInstance();

    // calculate signature size
    if (contentEstimated == 0) {
        contentEstimated = calculateEstimatedSignatureSize(certChain, tsc, ocsp, crlList);
    }

    byte[] encodedSig = calculateSignature(sgn, contentEstimated, messageDigest, cal, params, certChain, tsc,
            ocsp, sap);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Estimated size: " + contentEstimated);
        LOG.debug("Encoded length: " + encodedSig.length);
    }

    if (contentEstimated + 2 < encodedSig.length) {
        if (!secondTry) {
            int contentExact = encodedSig.length;
            LOG.warn(
                    "Estimated signature size too small, usinging accurate calculation (resulting in an extra signature computation).");

            if (LOG.isDebugEnabled()) {
                LOG.debug("Estimated size: " + contentEstimated + ", actual size: " + contentExact);
            }

            // try signing again
            return addSignatureToPDFDocument(crypto, params, pdfbytes, password, contentExact, request,
                    context);
        } else {
            // if we fail to get an accurate signature size on the second attempt, bail out (this shouldn't happen)
            throw new SignServerException("Failed to calculate signature size");
        }
    }

    byte[] paddedSig = new byte[contentEstimated];
    System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);

    PdfDictionary dic2 = new PdfDictionary();
    dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
    sap.close(dic2);
    reader.close();

    fout.close();
    return fout.toByteArray();
}

From source file:org.webpki.pdf.PDFSigner.java

License:Apache License

public byte[] addDocumentSignature(byte[] indoc, boolean certified) throws IOException {
    try {//from  www .j ava2  s . c om
        PdfReader reader = new PdfReader(indoc);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(8192);
        PdfStamper stp = PdfStamper.createSignature(reader, bout, '\0', null, true);

        for (Attachment file : attachments) {
            stp.addFileAttachment(file.description, file.data, "dummy", file.filename);
        }

        PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(null, signer.getCertificatePath(), null, PdfSignatureAppearance.WINCER_SIGNED);

        if (reason != null) {
            sap.setReason(reason);
        }
        if (location != null) {
            sap.setLocation(location);
        }

        if (enable_signature_graphics) {
            sap.setVisibleSignature(new Rectangle(100, 100, 400, 130), reader.getNumberOfPages(), null);
        }

        sap.setCertified(certified);

        //           sap.setExternalDigest (new byte[128], new byte[20], "RSA");
        sap.setExternalDigest(new byte[512], new byte[20], "RSA");
        sap.preClose();
        MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        byte buf[] = new byte[8192];
        int n;
        InputStream inp = sap.getRangeStream();
        while ((n = inp.read(buf)) > 0) {
            messageDigest.update(buf, 0, n);
        }
        byte hash[] = messageDigest.digest();
        PdfSigGenericPKCS sg = sap.getSigStandard();
        PdfLiteral slit = (PdfLiteral) sg.get(PdfName.CONTENTS);
        byte[] outc = new byte[(slit.getPosLength() - 2) / 2];
        PdfPKCS7 sig = sg.getSigner();
        sig.setExternalDigest(signer.signData(hash, AsymSignatureAlgorithms.RSA_SHA1), hash, "RSA");
        PdfDictionary dic = new PdfDictionary();
        byte[] ssig = sig.getEncodedPKCS7();
        System.arraycopy(ssig, 0, outc, 0, ssig.length);
        dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
        sap.close(dic);

        return bout.toByteArray();
    } catch (NoSuchAlgorithmException nsae) {
        throw new IOException(nsae.getMessage());
    } catch (DocumentException de) {
        throw new IOException(de.getMessage());
    }
}

From source file:org.xhtmlrenderer.pdf.ITextOutputDevice.java

License:Open Source License

private void writeNamedDestinations(RenderingContext c) {
    Map idMap = getSharedContext().getIdMap();
    if ((idMap != null) && (!idMap.isEmpty())) {
        PdfArray dests = new PdfArray();
        try {//  www .j  a  v a 2  s . c o m
            Iterator it = idMap.entrySet().iterator();
            while (it.hasNext()) {
                Entry entry = (Entry) it.next();

                Box targetBox = (Box) entry.getValue();

                if (targetBox.getStyle().isIdent(CSSName.FS_NAMED_DESTINATION, IdentValue.CREATE)) {
                    String anchorName = (String) entry.getKey();
                    dests.add(new PdfString(anchorName, PdfString.TEXT_UNICODE));

                    PdfDestination dest = createDestination(c, targetBox);
                    if (dest != null) {
                        PdfIndirectReference ref = _writer.addToBody(dest).getIndirectReference();
                        dests.add(ref);
                    }
                }
            }

            if (!dests.isEmpty()) {
                PdfDictionary nametree = new PdfDictionary();
                nametree.put(PdfName.NAMES, dests);
                PdfIndirectReference nameTreeRef = _writer.addToBody(nametree).getIndirectReference();

                PdfDictionary names = new PdfDictionary();
                names.put(PdfName.DESTS, nameTreeRef);
                PdfIndirectReference destinationsRef = _writer.addToBody(names).getIndirectReference();

                _writer.getExtraCatalog().put(PdfName.NAMES, destinationsRef);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:questions.forms.AddActionToField.java

public static void main(String[] args) {
    try {//w  w  w  .  j a  v a2s.  co m
        PdfReader reader = new PdfReader(RESOURCE);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        AcroFields form = stamper.getAcroFields();
        Item fd = form.getFieldItem("Who");
        PdfDictionary dict = (PdfDictionary) PdfReader.getPdfObject((PdfObject) fd.getWidgetRef(0));
        PdfDictionary aa = dict.getAsDict(PdfName.AA);
        if (aa == null)
            aa = new PdfDictionary();
        aa.put(new PdfName("Fo"),
                PdfAction.javaScript("app.alert('Who has got the focus!?');", stamper.getWriter()));
        dict.put(PdfName.AA, aa);
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.forms.ChangeTextFieldAlignment.java

public static void main(String[] args) {
    try {/*ww  w.  ja  va2  s .  co m*/
        PdfReader reader = new PdfReader(RESOURCE);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        AcroFields form = stamper.getAcroFields();
        PdfDictionary dict = form.getFieldItem("Who").getMerged(0);
        dict.put(PdfName.Q, new PdfNumber(1));
        form.setField("Who", "Center of the World");
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}