pdfviewerapplet.java

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

JAVA
238
字号
// $Id: PDFViewerApplet.java,v 1.15 2007/11/16 05:05:31 mike Exp $package org.faceless.pdf2.viewer2;import org.faceless.pdf2.PDF;import org.faceless.pdf2.PropertyManager;import org.faceless.pdf2.EncryptionHandler;import org.faceless.pdf2.StandardEncryptionHandler;import org.faceless.pdf2.viewer2.feature.About;import java.applet.*;import java.util.*;import java.awt.event.*;import java.net.URL;import java.io.IOException;import javax.swing.*;/** * An applet wrapping the {@link PDFViewer}. At it's simplest you can simply embed it in the * page using the <code>applet</code> tag, although since 2.8.5 this class can be usefully * controlled from JavaScript via LiveConnect. For instance, to instantiate an applet * that is controlled via JavaScript buttons instead of Java buttons: * <pre class="example" style="font-size:smaller"> * &lt;html&gt; *  &lt;head&gt; *   &lt;style&gt; *    applet { width:100%; height:500px; display:block } *    form   { text-align:center  } *   &lt;/style&gt; *   &lt;script&gt; *    function documentUpdated(event) { *      if (event.getType()=="redrawn" || event.getType()=="activated") { *        document.forms[0].pagenumber.value = event.getDocumentPanel().getPageNumber()+1; *      } *    } *   &lt;/script&gt; *  &lt;/head&gt; *  &lt;body&gt; *   &lt;applet code="org.faceless.pdf2.viewer2.PDFViewerApplet" name="pdfapplet" archive="bfopdf.jar" mayscript&gt; *    &lt;param name="pdf" value="test.pdf" /&gt; *    &lt;param name="feature.MultiWindow" value="false" /&gt; *    &lt;param name="feature.Toolbars" value="false" /&gt; *    &lt;param name="liveconnect.DocumentPanelListener" value="documentUpdated" /&gt; *   &lt;/applet&gt; *   &lt;form onsubmit="return false"&gt; *    &lt;input type="button" onclick="document.pdfapplet.runWidgetAction('PagePrevious')" value="&lt;&lt;"/&gt; *    &lt;input type="text" name="pagenumber" size="5" *        onchange="document.pdfapplet.getViewer().getActiveDocumentPanel().setPageNumber(this.value-1)"/&gt; *    &lt;input type="button" onclick="document.pdfapplet.runWidgetAction('PageNext')" value="&gt;&gt;"/&gt; *   &lt;/form&gt; *  &lt;/body&gt; * &lt;/html&gt; * </pre><p> * Things of note here are the initialization paramaters to the applet - the <code>feature.<i>nnn</i></code> * may be set to false to turn off an individual feature; the <code>pdf</code> attribute is set to load a PDF * from the specified URL on startup; and the <code>liveconnect.DocumentPanelListener</code> attribute is * set to the name of the JavaScript method that should be called whenever a {@link DocumentPanelEvent} is raised. * If specified, this method is called with the event object as a single parameter. This also requires the * <code>mayscript</code> attribute on the <code>applet</code> tag as seen here. * <br /><br /> * Other than that, controlling the applet can be done via the {@link #runWidgetAction} method for simple * widgets or, for more complex operations, the {@link #getViewer} method can be used to access and control * the {@link PDFViewer} object. * </p><p> * Bear in mind that although the applet is contained in a Signed Jar, any access to that * applet from unsigned JavaScript will be untrusted by default - which means no access to * the local filesystem, no printing and so on (although it is possible to * <a href="http://www.mozilla.org/projects/security/components/signed-scripts.html">sign the JavaScript</a> * to allow this). * </p> * <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 PDFViewerApplet extends JApplet implements DocumentPanelListener, PropertyManager{    private PDFViewer viewer;    private String listenercallback;    public void init() {        try {            String laf = UIManager.getSystemLookAndFeelClassName();            if (!"com.sun.java.swing.plaf.gtk.GTKLookAndFeel".equals(laf)) {                UIManager.setLookAndFeel(laf);            }            SwingUtilities.updateComponentTreeUI(this);        } catch (Throwable e) {}        try {            System.getProperty("user.home");            About.putStaticProperty("Applet", "Trusted");        } catch (Throwable e) {            About.putStaticProperty("Applet", "Untrusted from "+getDocumentBase());        }        List c = new ArrayList(ViewerFeature.getAllFeatures());        for (Iterator i = c.iterator();i.hasNext();) {            ViewerFeature feature = (ViewerFeature)i.next();            String name = feature.getName();            if ("false".equals(getProperty("feature."+name))) {                i.remove();            }        }        listenercallback = getProperty("liveconnect.DocumentPanelListener");        viewer = new PDFViewer(c);        viewer.setPropertyManager(this);        viewer.addDocumentPanelListener(this);        getContentPane().add(viewer);        addComponentListener(new ComponentAdapter() {            public void componentShown(ComponentEvent event) {                if (getProperty("pdf")!=null) {                    try {                        loadPDF(getProperty("pdf"), getProperty("password"));                    } catch (IOException e) {                        SuperJOptionPane.displayThrowable(getProperty("pdf"), e, PDFViewerApplet.this);                    }                }                for (int i=2;getProperty("pdf"+i)!=null;i++) {                    try {                        loadPDF(getProperty("pdf"+1), getProperty("password"+1));                    } catch (IOException e) {                        SuperJOptionPane.displayThrowable(getProperty("pdf"+i), e, PDFViewerApplet.this);                    }                }                PDFViewerApplet.this.removeComponentListener(this);            }        });    }    public URL getURLProperty(String key) throws java.net.MalformedURLException {        String property = getProperty(key);        return property==null ? null : new URL(getDocumentBase(), property);    }    public String getProperty(String key) {        return getParameter(key);    }    public String getAppletInfo() {        return "BFO PDF Viewer "+PDF.VERSION+": http://bfo.co.uk/products/pdf";    }    public String[][] getParameterInfo() {        Collection c = ViewerFeature.getAllFeatures();        String[][] x = new String[c.size()+3][];        int pos = 0;        for (Iterator i = c.iterator();i.hasNext();) {            String name = ((ViewerFeature)i.next()).getName();            x[pos++] = new String[] { "feature."+name, "boolean", "Enable the \""+name+"\" feature" };        }        x[pos++] = new String[] { "liveconnect.DocumentPanelListener", "String", "The name of the method to call when a DocumentPanelEvent is raised" };        x[pos++] = new String[] { "pdf", "String", "The URL of the PDF to load on startup" };        x[pos++] = new String[] { "pdf.n", "String", "Additional URLs of the PDF to load on startup (n>=2)" };        return x;    }    /**     * <p>     * Load a PDF from the specified URL. If the URL is relative, it is resolved     * based on the URL of the page containing the applet. Simply calls     * {@link #loadPDF(String, String) loadPDF(url, null)}.     * </p><p>     * Bear in mind if that any methods, including this one, that are called from JavaScript will     * run as if the applet was untrusted. Consequently this method cannot be called to load PDF's     * from the local filesystem.     * </p>     *     * @param url the URL of the PDF to load.     * @since 2.8.5     */    public void loadPDF(String url) throws IOException {        loadPDF(url, null);    }    /**     * <p>     * Load a PDF from the specified URL. If the URL is relative, it is resolved     * based on the URL of the page containing the applet. If the <code>password</code>     * parameter is not null then that password will be used if required, otherwise      * any required passwords or private keys will be prompted for - for finer control, the {@link PDFViewer#loadPDF(InputStream, EncryptionHandler[], String, File) PDFViewer.loadPDF()}     * method can be used.     * </p><p>     * Bear in mind if that any methods, including this one, that are called from JavaScript will     * run as if the applet was untrusted. Consequently this method cannot be called to load PDF's     * from the local filesystem.     * </p>     *     * @param url the URL of the PDF to load.     * @param password the password to use to open the PDF, or <code>null</code> to prompt if required.     * @since 2.8.6     */    public void loadPDF(String url, String password) throws IOException {        URL uurl = new URL(getDocumentBase(), url);        EncryptionHandler[] handlers;        if (password==null) {            handlers = new EncryptionHandler[2];            handlers[0] = new PasswordPromptEncryptionHandler(viewer);            handlers[1] = new PublicKeyPromptEncryptionHandler(viewer, viewer.getKeyStoreManager());        } else {            handlers = new EncryptionHandler[1];            handlers[0] = new StandardEncryptionHandler();            ((StandardEncryptionHandler)handlers[0]).setUserPassword(password);        }        viewer.loadPDF(uurl.openStream(), handlers, url, null);    }    /**     * Return the PDF Viewer embedded in this applet     * @since 2.8.5     */    public PDFViewer getViewer() {        return viewer;    }    /**     * Run the {@link ViewerWidget#action action()} method on the specified     * ViewerWidget. Typically this would be called from JavaScript to move     * between pages or similar widget-based actions.     * @since 2.8.5     */    public void runWidgetAction(String name) {        ViewerFeature feature = viewer.getFeature(name);        if (feature instanceof ViewerWidget) {            DocumentPanel panel = viewer.getActiveDocumentPanel();            if (panel!=null || !((ViewerWidget)feature).isDocumentRequired()) {                ((ViewerWidget)feature).action(new ViewerEvent(viewer, panel));            }        }    }    public void documentUpdated(DocumentPanelEvent event) {        if (listenercallback!=null) {            try {                netscape.javascript.JSObject.getWindow(this).call(listenercallback, new Object[] { event });            } catch (ClassCastException e) {    // Opera 9 on OS X                e.printStackTrace();            }        }    }}

⌨️ 快捷键说明

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