Search in sources :

Example 11 with ExceptionConverter

use of pdftk.com.lowagie.text.ExceptionConverter in project staplr by pridiltal.

the class PdfAcroForm method drawCheckBoxAppearences.

/**
 * @param field
 * @param value
 * @param llx
 * @param lly
 * @param urx
 * @param ury
 */
public void drawCheckBoxAppearences(PdfFormField field, String value, float llx, float lly, float urx, float ury) {
    BaseFont font = null;
    try {
        font = BaseFont.createFont(BaseFont.ZAPFDINGBATS, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
    float size = (ury - lly);
    PdfContentByte cb = writer.getDirectContent();
    PdfAppearance tpOn = cb.createAppearance(urx - llx, ury - lly);
    PdfAppearance tp2 = (PdfAppearance) tpOn.getDuplicate();
    tp2.setFontAndSize(font, size);
    tp2.resetRGBColorFill();
    field.setDefaultAppearanceString(tp2);
    tpOn.drawTextField(0f, 0f, urx - llx, ury - lly);
    tpOn.saveState();
    tpOn.resetRGBColorFill();
    tpOn.beginText();
    tpOn.setFontAndSize(font, size);
    tpOn.showTextAligned(PdfContentByte.ALIGN_CENTER, "4", (urx - llx) / 2, (ury - lly) / 2 - (size * 0.3f), 0);
    tpOn.endText();
    tpOn.restoreState();
    field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, value, tpOn);
    PdfAppearance tpOff = cb.createAppearance(urx - llx, ury - lly);
    tpOff.drawTextField(0f, 0f, urx - llx, ury - lly);
    field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", tpOff);
}
Also used : ExceptionConverter(pdftk.com.lowagie.text.ExceptionConverter)

Example 12 with ExceptionConverter

use of pdftk.com.lowagie.text.ExceptionConverter in project staplr by pridiltal.

the class AcroFields method splitDAelements.

private static Object[] splitDAelements(String da) {
    try {
        PRTokeniser tk = new PRTokeniser(PdfEncodings.convertToBytes(da, null));
        ArrayList stack = new ArrayList();
        Object[] ret = new Object[3];
        while (tk.nextToken()) {
            if (tk.getTokenType() == PRTokeniser.TK_COMMENT)
                continue;
            if (tk.getTokenType() == PRTokeniser.TK_OTHER) {
                String operator = tk.getStringValue();
                if (operator.equals("Tf")) {
                    if (stack.size() >= 2) {
                        ret[DA_FONT] = stack.get(stack.size() - 2);
                        ret[DA_SIZE] = new Float((String) stack.get(stack.size() - 1));
                    }
                } else if (operator.equals("g")) {
                    if (stack.size() >= 1) {
                        float gray = new Float((String) stack.get(stack.size() - 1)).floatValue();
                        if (gray != 0)
                            ret[DA_COLOR] = new GrayColor(gray);
                    }
                } else if (operator.equals("rg")) {
                    if (stack.size() >= 3) {
                        float red = new Float((String) stack.get(stack.size() - 3)).floatValue();
                        float green = new Float((String) stack.get(stack.size() - 2)).floatValue();
                        float blue = new Float((String) stack.get(stack.size() - 1)).floatValue();
                        ret[DA_COLOR] = new Color(red, green, blue);
                    }
                } else if (operator.equals("k")) {
                    if (stack.size() >= 4) {
                        float cyan = new Float((String) stack.get(stack.size() - 4)).floatValue();
                        float magenta = new Float((String) stack.get(stack.size() - 3)).floatValue();
                        float yellow = new Float((String) stack.get(stack.size() - 2)).floatValue();
                        float black = new Float((String) stack.get(stack.size() - 1)).floatValue();
                        ret[DA_COLOR] = new CMYKColor(cyan, magenta, yellow, black);
                    }
                }
                stack.clear();
            } else
                stack.add(tk.getStringValue());
        }
        return ret;
    } catch (IOException ioe) {
        throw new ExceptionConverter(ioe);
    }
}
Also used : ExceptionConverter(pdftk.com.lowagie.text.ExceptionConverter) Color(java.awt.Color) ArrayList(java.util.ArrayList) IOException(java.io.IOException)

Example 13 with ExceptionConverter

use of pdftk.com.lowagie.text.ExceptionConverter in project staplr by pridiltal.

the class AcroFields method setFieldProperty.

/**
 * Sets a field property. Valid property names are:
 * <p>
 * <ul>
 * <li>textfont - sets the text font. The value for this entry is a <CODE>BaseFont</CODE>.<br>
 * <li>textcolor - sets the text color. The value for this entry is a <CODE>java.awt.Color</CODE>.<br>
 * <li>textsize - sets the text size. The value for this entry is a <CODE>Float</CODE>.
 * <li>bgcolor - sets the background color. The value for this entry is a <CODE>java.awt.Color</CODE>.
 *     If <code>null</code> removes the background.<br>
 * <li>bordercolor - sets the border color. The value for this entry is a <CODE>java.awt.Color</CODE>.
 *     If <code>null</code> removes the border.<br>
 * </ul>
 * @param field the field name
 * @param name the property name
 * @param value the property value
 * @param inst an array of <CODE>int</CODE> indexing into <CODE>AcroField.Item.merged</CODE> elements to process.
 * Set to <CODE>null</CODE> to process all
 * @return <CODE>true</CODE> if the property exists, <CODE>false</CODE> otherwise
 */
public boolean setFieldProperty(String field, String name, Object value, int[] inst) {
    if (writer == null)
        throw new RuntimeException("This AcroFields instance is read-only.");
    try {
        Item item = (Item) fields.get(field);
        if (item == null)
            return false;
        InstHit hit = new InstHit(inst);
        if (name.equalsIgnoreCase("textfont")) {
            for (int k = 0; k < item.merged.size(); ++k) {
                if (hit.isHit(k)) {
                    PdfString da = (PdfString) PdfReader.getPdfObject(((PdfDictionary) item.merged.get(k)).get(PdfName.DA));
                    PdfDictionary dr = (PdfDictionary) PdfReader.getPdfObject(((PdfDictionary) item.merged.get(k)).get(PdfName.DR));
                    if (da != null && dr != null) {
                        Object[] dao = splitDAelements(da.toUnicodeString());
                        PdfAppearance cb = new PdfAppearance();
                        if (dao[DA_FONT] != null) {
                            BaseFont bf = (BaseFont) value;
                            PdfName psn = (PdfName) PdfAppearance.stdFieldFontNames.get(bf.getPostscriptFontName());
                            if (psn == null) {
                                psn = new PdfName(bf.getPostscriptFontName());
                            }
                            PdfDictionary fonts = (PdfDictionary) PdfReader.getPdfObject(dr.get(PdfName.FONT));
                            if (fonts == null) {
                                fonts = new PdfDictionary();
                                dr.put(PdfName.FONT, fonts);
                            }
                            PdfIndirectReference fref = (PdfIndirectReference) fonts.get(psn);
                            PdfDictionary top = (PdfDictionary) PdfReader.getPdfObject(reader.getCatalog().get(PdfName.ACROFORM));
                            markUsed(top);
                            dr = (PdfDictionary) PdfReader.getPdfObject(top.get(PdfName.DR));
                            if (dr == null) {
                                dr = new PdfDictionary();
                                top.put(PdfName.DR, dr);
                            }
                            markUsed(dr);
                            PdfDictionary fontsTop = (PdfDictionary) PdfReader.getPdfObject(dr.get(PdfName.FONT));
                            if (fontsTop == null) {
                                fontsTop = new PdfDictionary();
                                dr.put(PdfName.FONT, fontsTop);
                            }
                            markUsed(fontsTop);
                            PdfIndirectReference frefTop = (PdfIndirectReference) fontsTop.get(psn);
                            if (frefTop != null) {
                                if (fref == null)
                                    fonts.put(psn, frefTop);
                            } else if (fref == null) {
                                FontDetails fd;
                                if (bf.getFontType() == BaseFont.FONT_TYPE_DOCUMENT) {
                                    fd = new FontDetails(null, ((DocumentFont) bf).getIndirectReference(), bf);
                                } else {
                                    bf.setSubset(false);
                                    fd = writer.addSimple(bf);
                                    localFonts.put(psn.toString().substring(1), bf);
                                }
                                fontsTop.put(psn, fd.getIndirectReference());
                                fonts.put(psn, fd.getIndirectReference());
                            }
                            ByteBuffer buf = cb.getInternalBuffer();
                            buf.append(psn.getBytes()).append(' ').append(((Float) dao[DA_SIZE]).floatValue()).append(" Tf ");
                            if (dao[DA_COLOR] != null)
                                cb.setColorFill((Color) dao[DA_COLOR]);
                            PdfString s = new PdfString(cb.toString());
                            ((PdfDictionary) item.merged.get(k)).put(PdfName.DA, s);
                            ((PdfDictionary) item.widgets.get(k)).put(PdfName.DA, s);
                            markUsed((PdfDictionary) item.widgets.get(k));
                        }
                    }
                }
            }
        } else if (name.equalsIgnoreCase("textcolor")) {
            for (int k = 0; k < item.merged.size(); ++k) {
                if (hit.isHit(k)) {
                    PdfString da = (PdfString) PdfReader.getPdfObject(((PdfDictionary) item.merged.get(k)).get(PdfName.DA));
                    if (da != null) {
                        Object[] dao = splitDAelements(da.toUnicodeString());
                        PdfAppearance cb = new PdfAppearance();
                        if (dao[DA_FONT] != null) {
                            ByteBuffer buf = cb.getInternalBuffer();
                            buf.append(new PdfName((String) dao[DA_FONT]).getBytes()).append(' ').append(((Float) dao[DA_SIZE]).floatValue()).append(" Tf ");
                            cb.setColorFill((Color) value);
                            PdfString s = new PdfString(cb.toString());
                            ((PdfDictionary) item.merged.get(k)).put(PdfName.DA, s);
                            ((PdfDictionary) item.widgets.get(k)).put(PdfName.DA, s);
                            markUsed((PdfDictionary) item.widgets.get(k));
                        }
                    }
                }
            }
        } else if (name.equalsIgnoreCase("textsize")) {
            for (int k = 0; k < item.merged.size(); ++k) {
                if (hit.isHit(k)) {
                    PdfString da = (PdfString) PdfReader.getPdfObject(((PdfDictionary) item.merged.get(k)).get(PdfName.DA));
                    if (da != null) {
                        Object[] dao = splitDAelements(da.toUnicodeString());
                        PdfAppearance cb = new PdfAppearance();
                        if (dao[DA_FONT] != null) {
                            ByteBuffer buf = cb.getInternalBuffer();
                            buf.append(new PdfName((String) dao[DA_FONT]).getBytes()).append(' ').append(((Float) value).floatValue()).append(" Tf ");
                            if (dao[DA_COLOR] != null)
                                cb.setColorFill((Color) dao[DA_COLOR]);
                            PdfString s = new PdfString(cb.toString());
                            ((PdfDictionary) item.merged.get(k)).put(PdfName.DA, s);
                            ((PdfDictionary) item.widgets.get(k)).put(PdfName.DA, s);
                            markUsed((PdfDictionary) item.widgets.get(k));
                        }
                    }
                }
            }
        } else if (name.equalsIgnoreCase("bgcolor") || name.equalsIgnoreCase("bordercolor")) {
            PdfName dname = (name.equalsIgnoreCase("bgcolor") ? PdfName.BG : PdfName.BC);
            for (int k = 0; k < item.merged.size(); ++k) {
                if (hit.isHit(k)) {
                    PdfObject obj = PdfReader.getPdfObject(((PdfDictionary) item.merged.get(k)).get(PdfName.MK));
                    markUsed(obj);
                    PdfDictionary mk = (PdfDictionary) obj;
                    if (mk == null) {
                        if (value == null)
                            return true;
                        mk = new PdfDictionary();
                        ((PdfDictionary) item.merged.get(k)).put(PdfName.MK, mk);
                        ((PdfDictionary) item.widgets.get(k)).put(PdfName.MK, mk);
                        markUsed((PdfDictionary) item.widgets.get(k));
                    }
                    if (value == null)
                        mk.remove(dname);
                    else
                        mk.put(dname, PdfFormField.getMKColor((Color) value));
                }
            }
        } else
            return false;
        return true;
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
Also used : Color(java.awt.Color) IOException(java.io.IOException) DocumentException(pdftk.com.lowagie.text.DocumentException) ExceptionConverter(pdftk.com.lowagie.text.ExceptionConverter)

Example 14 with ExceptionConverter

use of pdftk.com.lowagie.text.ExceptionConverter in project staplr by pridiltal.

the class PdfPKCS7 method getAuthenticatedAttributeBytes.

/**
 * When using authenticatedAttributes the authentication process is different.
 * The document digest is generated and put inside the attribute. The signing is done over the DER encoded
 * authenticatedAttributes. This method provides that encoding and the parameters must be
 * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}.
 * <p>
 * A simple example:
 * <p>
 * <pre>
 * Calendar cal = Calendar.getInstance();
 * PdfPKCS7 pk7 = new PdfPKCS7(key, chain, null, "SHA1", null, false);
 * MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
 * byte buf[] = new byte[8192];
 * int n;
 * InputStream inp = sap.getRangeStream();
 * while ((n = inp.read(buf)) &gt; 0) {
 *    messageDigest.update(buf, 0, n);
 * }
 * byte hash[] = messageDigest.digest();
 * byte sh[] = pk7.getAuthenticatedAttributeBytes(hash, cal);
 * pk7.update(sh, 0, sh.length);
 * byte sg[] = pk7.getEncodedPKCS7(hash, cal);
 * </pre>
 * @param secondDigest the content digest
 * @param signingTime the signing time
 * @return the byte array representation of the authenticatedAttributes ready to be signed
 */
public byte[] getAuthenticatedAttributeBytes(byte[] secondDigest, Calendar signingTime) {
    try {
        ASN1EncodableVector attribute = new ASN1EncodableVector();
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(ID_CONTENT_TYPE));
        v.add(new DERSet(new ASN1ObjectIdentifier(ID_PKCS7_DATA)));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(ID_SIGNING_TIME));
        v.add(new DERSet(new DERUTCTime(signingTime.getTime())));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(ID_MESSAGE_DIGEST));
        v.add(new DERSet(new DEROctetString(secondDigest)));
        attribute.add(new DERSequence(v));
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ASN1OutputStream dout = new ASN1OutputStream(bOut);
        dout.writeObject(new DERSet(attribute));
        dout.close();
        return bOut.toByteArray();
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}
Also used : ExceptionConverter(pdftk.com.lowagie.text.ExceptionConverter) DERSequence(org.bouncycastle.asn1.DERSequence) DERUTCTime(org.bouncycastle.asn1.DERUTCTime) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ASN1OutputStream(org.bouncycastle.asn1.ASN1OutputStream) DERSet(org.bouncycastle.asn1.DERSet) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) DEROctetString(org.bouncycastle.asn1.DEROctetString) SignatureException(java.security.SignatureException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CRLException(java.security.cert.CRLException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 15 with ExceptionConverter

use of pdftk.com.lowagie.text.ExceptionConverter in project staplr by pridiltal.

the class PdfPKCS7 method setExternalDigest.

/**
 * Sets the digest/signature to an external calculated value.
 * @param digest the digest. This is the actual signature
 * @param RSAdata the extra data that goes into the data tag in PKCS#7
 * @param digestEncryptionAlgorithm the encryption algorithm. It may must be <CODE>null</CODE> if the <CODE>digest</CODE>
 * is also <CODE>null</CODE>. If the <CODE>digest</CODE> is not <CODE>null</CODE>
 * then it may be "RSA" or "DSA"
 */
public void setExternalDigest(byte[] digest, byte[] RSAdata, String digestEncryptionAlgorithm) {
    externalDigest = digest;
    externalRSAdata = RSAdata;
    if (digestEncryptionAlgorithm != null) {
        if (digestEncryptionAlgorithm.equals("RSA")) {
            this.digestEncryptionAlgorithm = ID_RSA;
        } else if (digestEncryptionAlgorithm.equals("DSA")) {
            this.digestEncryptionAlgorithm = ID_DSA;
        } else
            throw new ExceptionConverter(new NoSuchAlgorithmException("Unknown Key Algorithm " + digestEncryptionAlgorithm));
    }
}
Also used : ExceptionConverter(pdftk.com.lowagie.text.ExceptionConverter) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

ExceptionConverter (pdftk.com.lowagie.text.ExceptionConverter)46 IOException (java.io.IOException)34 DocumentException (pdftk.com.lowagie.text.DocumentException)17 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 SignatureException (java.security.SignatureException)5 InvalidKeyException (java.security.InvalidKeyException)4 NoSuchProviderException (java.security.NoSuchProviderException)4 CRLException (java.security.cert.CRLException)4 CertificateException (java.security.cert.CertificateException)4 ArrayList (java.util.ArrayList)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)3 ASN1OutputStream (org.bouncycastle.asn1.ASN1OutputStream)3 DEROctetString (org.bouncycastle.asn1.DEROctetString)3 DERTaggedObject (org.bouncycastle.asn1.DERTaggedObject)3 Color (java.awt.Color)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 HashMap (java.util.HashMap)2 Iterator (java.util.Iterator)2