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

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

Introduction

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

Prototype

public void put(final PdfName key, final 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.orbisgis.core_export.GeoSpatialPDF.java

License:Open Source License

/**
 * This method is used to georeference the pdf.
 * Note : The CRS is not yet supported.// w  w  w . j a v a  2s  . c om
 *
 * @param writer
 * @param mt
 * @throws IOException
 * @throws DocumentException
 */
public void georefPdf(PdfWriter writer, MapTransform mt) throws IOException, DocumentException {

    PdfStructureTreeRoot tree = writer.getStructureTreeRoot();

    //the part of the document where maps are displayed
    float mapWidth = width;
    float mapHeight = height;
    float mapLX = 0;
    float mapLY = 0;

    //ViewPort Dictionary
    PdfDictionary viewPortDict = new PdfDictionary();
    viewPortDict.put(PdfName.TYPE, new PdfName("Viewport"));
    viewPortDict.put(PdfName.BBOX, new PdfRectangle(mapLX, mapLY, mapLX + mapWidth, mapLY + mapHeight));
    viewPortDict.put(PdfName.NAME, new PdfString("Layers"));

    //Measure dictionary
    PdfDictionary measureDict = new PdfDictionary();
    measureDict.put(PdfName.TYPE, new PdfName("Measure"));
    measureDict.put(PdfName.SUBTYPE, new PdfName("GEO"));

    //Bounds
    PdfArray bounds = new PdfArray();
    bounds.add(new PdfNumber(0));
    bounds.add(new PdfNumber(0));
    bounds.add(new PdfNumber(1));
    bounds.add(new PdfNumber(0));
    bounds.add(new PdfNumber(1));
    bounds.add(new PdfNumber(1));
    bounds.add(new PdfNumber(0));
    bounds.add(new PdfNumber(1));

    measureDict.put(new PdfName("Bounds"), bounds);

    //GPTS
    Envelope adjustedBbox = mt.getAdjustedExtent();

    if (!adjustedBbox.isNull()) {

        //ly lx ly ux uy ux uy lx
        PdfArray gptsTable = new PdfArray();
        gptsTable.add(new PdfNumber(((Double) adjustedBbox.getMinY()).toString()));
        gptsTable.add(new PdfNumber(((Double) adjustedBbox.getMinX()).toString()));
        gptsTable.add(new PdfNumber(((Double) adjustedBbox.getMinY()).toString()));
        gptsTable.add(new PdfNumber(((Double) adjustedBbox.getMaxX()).toString()));
        gptsTable.add(new PdfNumber(((Double) adjustedBbox.getMaxY()).toString()));
        gptsTable.add(new PdfNumber(((Double) adjustedBbox.getMaxX()).toString()));
        gptsTable.add(new PdfNumber(((Double) adjustedBbox.getMaxY()).toString()));
        gptsTable.add(new PdfNumber(((Double) adjustedBbox.getMinX()).toString()));

        measureDict.put(new PdfName("GPTS"), gptsTable);

        //The CRS will be added when the mapcontext will support it.

        //            //GCS Geospatial Coordinate system
        //            PdfDictionary gcsDict = new PdfDictionary();
        //            if (context.getBbox().getCrs() != null) {
        //
        //                if (context.getBbox().getCrs().getType() != null) {
        //                    gcsDict.put(PdfName.TYPE, new PdfName(context.getBbox().getCrs().getType()));
        //                } else {
        //                    LOGGER.warn("No type of crs : the pdf cannot be georeferenced");
        //                    return;
        //                }
        //
        //                if (context.getBbox().getCrs().getEpsg() != 0) {
        //                    gcsDict.put(new PdfName("EPSG"), new PdfNumber(context.getBbox().getCrs().getEpsg()));
        //                } else {
        //                    LOGGER.warn("No epsg : the pdf cannot be georeferenced");
        //                    return;
        //                }
        //
        //
        //            } else {
        //                LOGGER.warn("No crs :  the pdf cannot be georeferenced");
        //
        //            }
        //
        //            measureDict.put(new PdfName("GCS"), gcsDict);
    } else {
        LOGGER.warn("Envelope of bbox null : the pdf cannot be georeferenced");

    }

    //PDU : array of units
    PdfArray pdu = new PdfArray();
    pdu.add(new PdfName("KM"));
    pdu.add(new PdfName("SQKM"));
    pdu.add(new PdfName("DEG"));

    measureDict.put(new PdfName("PDU"), pdu);

    //LPTS
    PdfArray lptsTable = new PdfArray();
    lptsTable.add(new PdfNumber(0));
    lptsTable.add(new PdfNumber(0));
    lptsTable.add(new PdfNumber(1));
    lptsTable.add(new PdfNumber(0));
    lptsTable.add(new PdfNumber(1));
    lptsTable.add(new PdfNumber(1));
    lptsTable.add(new PdfNumber(0));
    lptsTable.add(new PdfNumber(1));

    measureDict.put(new PdfName("LPTS"), lptsTable);

    viewPortDict.put(new PdfName("Measure"), measureDict);

    PdfStructureElement top = new PdfStructureElement(tree, new PdfName("VP"));
    top.putAll(viewPortDict);
}

From source file:org.orbisgis.core_export.PdfRendererWithAttributes.java

License:Open Source License

@Override
public void beginFeature(long id, ResultSet rs) {
    try {//from  w  w w .j  a va  2  s  .  c  om
        String attributeName;
        attributeName = rs.getString(fieldName);
        PdfStructureElement e = new PdfStructureElement(top, new PdfName(attributeName));
        PdfDictionary userProperties = new PdfDictionary();
        userProperties.put(PdfName.O, PdfName.USERPROPERTIES);
        PdfArray properties = new PdfArray();
        SpatialResultSetMetaData metaData = rs.getMetaData().unwrap(SpatialResultSetMetaData.class);

        int geometryField = metaData.getFirstGeometryFieldIndex();
        PdfDictionary property = new PdfDictionary();
        property.put(PdfName.N, new PdfString(metaData.getColumnName(geometryField)));
        property.put(PdfName.V, new PdfString(rs.getString(geometryField)));
        properties.add(property);

        userProperties.put(PdfName.P, properties);
        e.put(PdfName.A, userProperties);

        pTemp = cb.createTemplate(width, height);
        cb.beginMarkedContentSequence(e);

    } catch (SQLException ex) {
        Logger.getLogger(PdfRendererWithAttributes.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.sejda.impl.itext5.component.AbstractPdfCopier.java

License:Open Source License

public void addPage(PdfReader reader, int pageNumber, PdfRectangle cropBox) throws TaskException {
    PdfImportedPage page = pdfCopy.getImportedPage(reader, pageNumber);
    PdfDictionary dictionary = reader.getPageN(pageNumber);
    dictionary.put(PdfName.MEDIABOX, cropBox);
    dictionary.put(PdfName.CROPBOX, cropBox);
    addPage(page);/*from w  w w. j  a  va 2 s  .c  o  m*/
}

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

License:Open Source License

/**
 * apply the rotation to the given page if necessary
 * /*from   w  w  w. j  av  a2 s. c  o m*/
 * @param pageNmber
 */
private void apply(int pageNmber) {
    if (rotation.accept(pageNmber)) {
        int pageRotation = reader.getPageRotation(pageNmber);
        PdfDictionary dictionary = reader.getPageN(pageNmber);
        dictionary.put(PdfName.ROTATE,
                new PdfNumber(rotation.getRotation().addRotation(getRotation(pageRotation)).getDegrees()));
    }
}

From source file:org.sinekartads.core.pdf.PDFTools.java

License:Open Source License

public static FinalizedSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> sign(
        SignedSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> signedSignature,
        //                                   X509Certificate certificate, 
        InputStream is, OutputStream os) throws SignatureException {
    ////      signAndMark(doc, certificate, is, os, null, null, null, null, null);
    //      signAndMark(signatureInfo, certificate, is, os, null, null, null);
    //   }// w  ww . j a v a  2 s .c  o m
    //
    //   public static void signAndMark(PDFSignatureInfo doc,
    //         X509Certificate certificate, InputStream is, OutputStream os,
    //         String tsaUrl, String tsaUser, String tsaPassword) {
    ////      signAndMark(doc, certificate, is, os, tsaUrl, tsaUser, tsaPassword, null, null);
    ////   }
    ////   
    ////   public static void signAndMark(DigitalSignatureDocument doc,
    ////         X509Certificate certificate, InputStream is, OutputStream os,
    ////         String tsaUrl, String tsaUser, String tsaPassword, Collection<CrlClient> crlList, OcspClient ocspClient) {
    try {
        PDFSignatureInfo signature = (PDFSignatureInfo) signedSignature;
        TSAClient tsaClient = null;

        TsRequestInfo tsRequest = signature.getTsRequest();
        if (tsRequest != null && StringUtils.isNotBlank(tsRequest.getTsUrl())) {
            tsaClient = new TSAClientBouncyCastle(tsRequest.getTsUrl(), tsRequest.getTsUsername(),
                    tsRequest.getTsPassword());
        }
        //         if (tsaUrl!=null) {
        //            tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPassword);
        //         }

        int estimatedSize = 0;
        CryptoStandard sigtype = CryptoStandard.CMS;

        // creo il reader del pdf
        PdfReader reader = new PdfReader(is);

        // creo lo stamper (se il pdf e' gia' firmato, controfirma,
        // altrimenti firma
        PdfStamper stamper = null;
        if (isPdfSigned(reader)) {
            if (tracer.isDebugEnabled())
                tracer.debug("document already signed, i will apply another sign");
            stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
        } else {
            if (tracer.isDebugEnabled())
                tracer.debug("document never signed before, this is first");
            stamper = PdfStamper.createSignature(reader, os, '\0');
        }

        // questo e' il certificato su cui lavorare
        Certificate[] chain = signature.getRawX509Certificates();
        //         Certificate[] chain = new Certificate[1];
        //         chain[0] = certificate;

        // creo la signature apparence
        PdfSignatureAppearance sap = stamper.getSignatureAppearance();
        ExternalDigest externalDigest = new BouncyCastleDigest();

        // inizio codice copiato da MakeSignature

        //         Collection<byte[]> crlBytes = null;
        //           int i = 0;
        //           while (crlBytes == null && i < chain.length)
        //              crlBytes = MakeSignature.processCrl(chain[i++], crlList);
        if (estimatedSize == 0) {
            estimatedSize = 8192;
            //               if (crlBytes != null) {
            //                   for (byte[] element : crlBytes) {
            //                       estimatedSize += element.length + 10;
            //                   }
            //               }
            //               if (ocspClient != null)
            estimatedSize += 4192;
            //               if (tsaClient != null)
            estimatedSize += 4192;
        }
        sap.setCertificate(chain[0]);
        sap.setReason(signature.getReason());
        sap.setLocation(signature.getLocation());

        Calendar cal = Calendar.getInstance();
        cal.setTime(signature.getSigningTime());
        sap.setSignDate(cal);
        sap.getStamper().setUnicodeModDate(signature.getUnicodeModDate());
        sap.getStamper().setFileId(signature.getFileId());

        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
        dic.setReason(sap.getReason());
        dic.setLocation(sap.getLocation());
        dic.setContact(sap.getContact());
        dic.setDate(new PdfDate(sap.getSignDate())); // time-stamp will over-rule this
        sap.setCryptoDictionary(dic);

        HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
        exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));
        sap.preClose(exc);

        String hashAlgorithm = signature.getDigestAlgorithm().getName();
        PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, BouncyCastleProvider.PROVIDER_NAME,
                externalDigest, false);
        InputStream data = sap.getRangeStream();
        byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm));
        //           byte[] ocsp = null;
        //           if (chain.length >= 2 && ocspClient != null) {
        //               ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null);
        //           }
        sgn.setExternalDigest(signature.getDigitalSignature(), null, "RSA");

        //           byte[] encodedSig = sgn.getEncodedPKCS7(hash, _getSignDate(doc.getSignDate()), tsaClient, ocsp, crlBytes, sigtype);
        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsaClient, null, null, sigtype);

        if (estimatedSize + 2 < encodedSig.length)
            throw new IOException("Not enough space");

        ASN1EncodableVector extraDataVectorEncoding = new ASN1EncodableVector();
        // 
        extraDataVectorEncoding.add(new DERObjectIdentifier("1.2.840.114283")); // encoding attribute 
        extraDataVectorEncoding.add(new DERGeneralString("115.105.110.101.107.97.114.116.97"));

        // applico la firma al PDF
        byte[] extraDataVectorEncodingBytes = new DERSequence(new DERSequence(extraDataVectorEncoding))
                .getEncoded();

        byte[] paddedSig = new byte[estimatedSize];
        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
        System.arraycopy(extraDataVectorEncodingBytes, 0, paddedSig, encodedSig.length,
                extraDataVectorEncodingBytes.length); // encoding attribute

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

        // this should be already done, but ...
        // closing streams
        try {
            is.close();
        } catch (IOException e) {
            tracer.error("error on input stream", e);
        }
        try {
            os.flush();
        } catch (IOException e) {
            tracer.error("error on output stream", e);
        }
        try {
            os.close();
        } catch (IOException e) {
            tracer.error("error on output stream", e);
        }
        return signature.finalizeSignature();
        //      } catch (MarkFailedException e) {
        //         throw e;
    } catch (Exception e) {
        tracer.error("Unable to sign PDF.", e);
        throw new SignatureException("Unable to sign PDF.", e);
    }
}

From source file:pdf.Sign.java

License:Open Source License

private String doSignPdf(String pdfFile, String pdfFileSigned) {
    try {//from  w  ww  . j  av a 2s  . c o m
        PdfReader reader = new PdfReader(pdfFile);
        FileOutputStream fout = new FileOutputStream(pdfFileSigned);
        PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
        PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(null, _chain, null, PdfSignatureAppearance.SELF_SIGNED);
        sap.setReason("Declaratie unica");
        sap.setVisibleSignature(new Rectangle(500, 775, 600, 675), 1, null);
        sap.setExternalDigest(
                new byte[((RSAPublicKey) _certAlias._cert.getPublicKey()).getModulus().bitLength() / 8], null,
                "RSA");
        sap.preClose();
        byte[] content = streamToByteArray(sap.getRangeStream());
        Signature signature = Signature.getInstance("SHA1withRSA", _etpkcs11);
        signature.initSign((PrivateKey) _privateKey);
        signature.update(content);
        byte[] signatureBytes = signature.sign();
        // Self-Sign mode
        PdfPKCS7 sig = sap.getSigStandard().getSigner();
        sig.setExternalDigest(signatureBytes, null, "RSA");
        PdfDictionary dic = new PdfDictionary();
        dic.put(PdfName.CONTENTS, new PdfString(sig.getEncodedPKCS1()).setHexWriting(true));
        sap.close(dic);
    } catch (FileNotFoundException ex) {
        return ex.toString();
    } catch (ProviderException ex) {
        if (ex.getMessage().equals("Initialization failed")) {
            return ex.toString()
                    + " (Probabil aveti un alt tip de SmartCard conectat. Deconectati alte tipuri de SmartCarduri (daca exista) si folositi optiunea \"*autoDetect\")";
        } else if (ex.getMessage().equals("Error parsing configuration")) {
            return ex.toString()
                    + " (Calea catre driverul SmartCardului (care se afla inscrisa in fisierul .cfg corespunzator acestuia) contine unul din urmatoarele caractere: \"~()\". Solutie: Copiati continutul intregului folder in alta locatie si modificati corespunzator calea din fisierul .cfg. (vezi si http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6581254))";
        }
        return ex.toString();
    } catch (NoSuchAlgorithmException ex) {
        return ex.toString();
    } catch (IOException ex) {
        return ex.toString();
    } catch (DocumentException ex) {
        return ex.toString();
    } catch (InvalidKeyException ex) {
        return ex.toString();
    } catch (SignatureException ex) {
        return ex.toString();
    } catch (Throwable ex) {
        return ex.toString();
    } finally {
        //wwww: eliminare key pt a putea introduce un nou pin
        //            String str = pin.getPassword().toString();
        //            pin.destroy();
        //            Security.removeProvider(_etpkcs11.getName());//"SunPKCS11-SmartCard");
        //wwww
    }
    return "";
}

From source file:pl.edu.icm.cermine.structure.ITextCharacterExtractor.java

License:Open Source License

/**
 * Processes PDF's fonts dictionary. During the process alternative names
 * of Standard 14 Fonts are changed to the standard ones, provided that
 * the font definition doesn't include Widths array.
 *
 * Font dictionary in PDF file often includes an array of individual glyphs' widths.
 * Widths array is always required except for the Standard 14 Fonts, which widths
 * are kept by iText itself. Unfortunately, if the font uses alternative name instead of
 * standard one (see PDF Reference 1.7, table H.3), iText doesn't recognize the font as
 * one of the Standard 14 Fonts, and is unable to determine glyphs widths. In such cases
 * this method will change alternative names to standard ones before PDF's parsing process
 *//* ww w.  j  av  a 2s.co  m*/
private void processAlternativeFontNames(PdfDictionary resources) {
    if (resources == null) {
        return;
    }
    PdfDictionary fontsDictionary = resources.getAsDict(PdfName.FONT);

    if (fontsDictionary == null) {
        return;
    }
    for (PdfName pdfFontName : fontsDictionary.getKeys()) {
        if (!(fontsDictionary.get(pdfFontName) instanceof PRIndirectReference)) {
            return;
        }
        PRIndirectReference indRef = (PRIndirectReference) fontsDictionary.get(pdfFontName);
        if (!(PdfReader.getPdfObjectRelease(indRef) instanceof PdfDictionary)) {
            return;
        }
        PdfDictionary fontDictionary = (PdfDictionary) PdfReader.getPdfObjectRelease(indRef);

        PdfName baseFont = fontDictionary.getAsName(PdfName.BASEFONT);
        if (baseFont != null) {
            String fontName = PdfName.decodeName(baseFont.toString());
            if (fontDictionary.getAsArray(PdfName.WIDTHS) == null
                    && ALT_TO_STANDART_FONTS.containsKey(fontName)) {
                fontDictionary.put(PdfName.BASEFONT, ALT_TO_STANDART_FONTS.get(fontName));
            }
        }
    }
}

From source file:pl.edu.icm.cermine.structure.ITextCharacterExtractor.java

License:Open Source License

private void processAlternativeColorSpace(PdfDictionary resources) {
    if (resources == null) {
        return;//from   www  .  j a v  a 2 s .c  om
    }
    PdfDictionary csDictionary = resources.getAsDict(PdfName.COLORSPACE);
    if (csDictionary == null) {
        return;
    }
    for (PdfName csName : csDictionary.getKeys()) {
        if (csDictionary.getAsArray(csName) != null) {
            csDictionary.put(csName, PdfName.DEVICEGRAY);
        }
    }
}