formblanksignaturewidgetfactory.java

来自「Java生成PDF Java生成PDF Java生成PDF」· Java 代码 · 共 222 行

JAVA
222
字号
// $Id: FormBlankSignatureWidgetFactory.java,v 1.14 2007/11/16 00:58:51 mike Exp $package org.faceless.pdf2.viewer2.feature;import org.faceless.pdf2.viewer2.*;import org.faceless.pdf2.*;import org.faceless.pdf2.Event;import javax.swing.*;import javax.swing.border.*;import java.awt.*;import java.security.*;import java.security.cert.*;import java.security.cert.Certificate;import java.io.*;import javax.swing.filechooser.FileFilter;import java.util.*;import java.text.*;import java.awt.event.*;/** * Create annotations to handle {@link WidgetAnnotation} objects belonging to unsigned {@link FormSignature} * fields. As supplied, this class will prompt the user for a {@link KeyStore} and and then to select the * alias and password required to sign the PDF, but it's possible to create an instance of this factory that * has any one of these fields pre-set. Then just remove the default <code>FormBlankSignatureWidgetFactory</code> * from the features passed in to the {@link PDFViewer} constructor and replace it with that new instance. * The name of this feature is "FormBlankSignatureWidgetFactory". * <p><i>This code is copyright the Big Faceless Organization. You're welcome to use, modify and distribute it in any form in your own projects, provided those projects continue to make use of the Big Faceless PDF library.</i></p> * @since 2.8 */public class FormBlankSignatureWidgetFactory extends AnnotationComponentFactory{    private PDFViewer viewer;    private KeyStoreManager keystoremanager;    private SignatureHandlerFactory handlerfactory;    private String timestampserver;    private String alias, reason, location, name;    private transient char[] password;    private int certificationtype;    /**     * Create a new FormBlankSignatureWidgetFactory     */    public FormBlankSignatureWidgetFactory() {        super("FormBlankSignatureWidgetFactory");    }    public void initialize(PDFViewer viewer) {        this.viewer = viewer;    }    public boolean matches(PDFAnnotation annot) {        return annot instanceof WidgetAnnotation && ((WidgetAnnotation)annot).getField() instanceof FormSignature && ((FormSignature)((WidgetAnnotation)annot).getField()).getState()==FormSignature.STATE_BLANK;    }    public JComponent createComponent(final PagePanel pagepanel, PDFAnnotation annot) {        final WidgetAnnotation widget = (WidgetAnnotation)annot;        final DocumentPanel docpanel = pagepanel.getDocumentPanel();        final FormSignature field = (FormSignature)widget.getField();        final JComponent comp = new JPanel() {            public void paintComponent(Graphics g) {                 g.setColor(Color.white);                 g.fillRect(0, 0, getWidth(), getHeight());                 AnnotationComponentFactory.paintComponent(this, "N", g);                 if (isFocusOwner()) {                     ((Graphics2D)g).setStroke(new BasicStroke(1, 0, 0, 1, new float[] { 1, 1 }, 0));                     g.setColor(Color.gray);                     g.drawRect(2, 2, getWidth()-6, getHeight()-6);                 }            }        };        if (!field.isReadOnly()) {            comp.setToolTipText(field.getDescription());            comp.addMouseListener(new MouseListener() {                public void mouseEntered(MouseEvent event) {                    comp.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));                }                public void mouseExited(MouseEvent event) {                    comp.setCursor(Cursor.getDefaultCursor());                }                public void mousePressed(MouseEvent event) { }                public void mouseReleased(MouseEvent event) { }                public void mouseClicked(MouseEvent event) {                    try {                        sign(field, docpanel);                    } catch (Exception e) {                        SuperJOptionPane.displayThrowable(SuperJOptionPane.getLocalizedString("Error"), e, docpanel);                    }                }            });            comp.addFocusListener(new FocusListener() {                public void focusGained(FocusEvent event) {                    comp.repaint();                    docpanel.runAction(widget.getAction(Event.FOCUS));                }                public void focusLost(FocusEvent event) {                    comp.repaint();                    docpanel.runAction(widget.getAction(Event.BLUR));                }            });        }        FormTextWidgetFactory.createOtherChange(docpanel, field);        return comp;    }    /**     * Set the reason for signing, which may be null.     * @param reason the signing reason     */    public void setReason(String reason) {        this.reason = reason;    }    /**     * Set the location of the signing, which may be null.     * @param location the signers location     */    public void setLocation(String location) {        this.location = location;    }    /**     * Set the name of the individual applying the signature. If not set     * the name will be take from the X.509 certificate used to sign.     * @param name the signers name     */    public void setName(String name) {        this.name = name;    }    /**     * Set the certification type     * @param type one of {@link FormSignature#CERTIFICATION_UNCERTIFIED}, {@link FormSignature#CERTIFICATION_NOCHANGES}, {@link FormSignature#CERTIFICATION_ALLOWFORMS} or {@link FormSignature#CERTIFICATION_ALLOWCOMMENTS}     */    public void setCertificationType(int type) {        this.certificationtype = type;    }    /**     * Set the alias to use from the KeyStore. If not specified (the     * default) the user will be optionally be prompted with a list of     * aliases available in the KeyStore.     * @param alias the alias     * @param password the password to use to extract the key     */    public void setAlias(String alias, char[] password) {        this.alias = alias;        this.password = password;    }    /**     * Set the {@link KeyStoreManager}     * @param manager the KeyStoreManager to use     * @since 2.8.3     */    public void setKeyStoreManager(KeyStoreManager manager) {        this.keystoremanager = manager;    }    private KeyStoreManager getKeyStoreManager() {        if (viewer!=null) {            return viewer.getKeyStoreManager();        } else {            if (keystoremanager==null) {                keystoremanager = KeyStoreManager.createDefaultKeyStoreManager(null);            }            return keystoremanager;        }    }    /**     * Set the {@link SignatureHandlerFactory} to be used to sign this PDF. This     * can be used to set custom features like key size, TimeStamp server and     * more. If not set a default {@link AcrobatSignatureHandlerFactory} is used.     * @param factory the factory     */    public void setSignatureHandlerFactory(SignatureHandlerFactory factory) {        this.handlerfactory = factory;    }    /**     * Sign the field.     * @param field the Signature Field to sign     * @param panel the panel     */    public void sign(FormSignature field, final DocumentPanel panel) throws IOException, GeneralSecurityException {        if (field.getState()==FormSignature.STATE_PENDING) {            JOptionPane.showMessageDialog(panel, SuperJOptionPane.getLocalizedString("PendingSignature"), SuperJOptionPane.getLocalizedString("Alert"), JOptionPane.INFORMATION_MESSAGE);            return;        }        if (handlerfactory==null) {            handlerfactory = new AcrobatSignatureHandlerFactory();        }        KeyStoreManager keystoremanager = getKeyStoreManager();        KeyStore keystore = keystoremanager.getKeyStore();        Map map = new HashMap();        map.put("Name", name);        map.put("Reason", reason);        map.put("Location", location);        if (alias!=null) {            map.put("Alias", alias);            map.put("Password", password);        } else {            map = keystoremanager.showSigningKeySelectionDialog(alias, password, map);        }        if (map!=null) {            String alias = (String)map.get("Alias");            char[] password = (char[])map.get("Password");            String reason = (String)map.get("Reason");            String name = (String)map.get("Name");            String location = (String)map.get("Location");            field.sign(keystore, alias, password, handlerfactory);            field.setCertificationType(certificationtype, null);            if (reason!=null) field.setReason(reason);            if (location!=null) field.setLocation(location);            if (name==null && field.getSignatureHandler() instanceof PKCS7SignatureHandler) {                name = FormSignature.getSubjectField(((PKCS7SignatureHandler)field.getSignatureHandler()).getCertificates()[0], "CN");            }            if (name!=null) field.setName(name);        }    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?