documentpanel.java

来自「Java生成PDF Java生成PDF Java生成PDF」· Java 代码 · 共 671 行 · 第 1/2 页

JAVA
671
字号
            tabbedpane = new JTabbedPane(JTabbedPane.LEFT);            tabbedpane.setTabPlacement(JTabbedPane.TOP);            tabbedpane.setMinimumSize(new Dimension(0, 0));            tabbedpane.addChangeListener(new ChangeListener() {                public void stateChanged(ChangeEvent event) {                    if (tabbedpane.getWidth()>thresholdsize) {                        Component comp = tabbedpane.getSelectedComponent();                        for (int i=0;i<tabbedpane.getTabCount();i++) {                            Component kid = tabbedpane.getComponentAt(i);                            if (kid!=comp && kid instanceof SidePanel) {                                ((SidePanel)kid).panelHidden();                            }                        }                        if (comp instanceof SidePanel) ((SidePanel)comp).panelVisible();                    }                }            });            splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tabbedpane, viewport);            splitpane.setOneTouchExpandable(true);            splitpane.setDividerSize(15);            splitpane.setResizeWeight(0);            thresholdsize = 50;            preferredsize = "apple.laf.AquaLookAndFeel".equals(UIManager.getSystemLookAndFeelClassName()) ? 130 : 120;            splitpane.addPropertyChangeListener(new java.beans.PropertyChangeListener() {                public void propertyChange(java.beans.PropertyChangeEvent event) {                    if (event.getPropertyName().equals("dividerLocation")) {                        int newvalue = ((Integer)event.getNewValue()).intValue();                        if (newvalue >= preferredsize) {                            Component comp = tabbedpane.getSelectedComponent();                            for (int i=0;i<tabbedpane.getTabCount();i++) {                                Component kid = tabbedpane.getComponentAt(i);                                if (kid!=comp && kid instanceof SidePanel) {                                    ((SidePanel)kid).panelHidden();                                }                            }                            if (comp instanceof SidePanel) ((SidePanel)comp).panelVisible();                        } else if (newvalue > thresholdsize) {                            splitpane.setDividerLocation(Math.min(splitpane.getMaximumDividerLocation(), preferredsize));                        } else {                            splitpane.setDividerLocation(splitpane.getMinimumDividerLocation());                        }                    }                }            });            Map oldpanels = panels;            panels = new LinkedHashMap();            for (Iterator i = panelfactories.iterator();i.hasNext();) {                SidePanelFactory panelfactory = (SidePanelFactory)i.next();                if (panelfactory.isSidePanelRequired(pdf)) {                    String name = panelfactory.getDisplayName();                    SidePanel panel = (SidePanel)oldpanels.get(name);                    if (panel!=null) {                        oldpanels.remove(panel);                    } else {                        panel = panelfactory.createSidePanel();                    }                    if (panel!=null) panels.put(name, panel);                }            }            for (Iterator i = oldpanels.values().iterator();i.hasNext();) {                ((SidePanel)i.next()).setDocumentPanel(null);            }            tabbedpane.removeAll();            if (panels.isEmpty()) {                add(viewport, BorderLayout.CENTER);            } else {                splitpane.setDividerLocation(preferredsize);                Thread.currentThread().yield();                Thread.currentThread().yield();                for (Iterator i = panels.entrySet().iterator();i.hasNext();) {                    Map.Entry e = (Map.Entry)i.next();                    String name = (String)e.getKey();                    tabbedpane.addTab(SuperJOptionPane.getLocalizedString(name), null, (Component)e.getValue(), name);                }                splitpane.setTopComponent(tabbedpane);                splitpane.setBottomComponent(viewport);                add(splitpane, BorderLayout.CENTER);                Object pagemode = pdf.getOption("pagemode");                if ("UseOutlines".equals(pagemode) && panels.containsKey("Bookmarks")) {                    setSelectedSidePanel("Bookmarks");                } else if ("UseThumbs".equals(pagemode) && panels.containsKey("Pages")) {                    setSelectedSidePanel("Pages");                } else {                    setSelectedSidePanel(null);                }            }            for (Iterator i = panels.values().iterator();i.hasNext();) {                ((SidePanel)i.next()).setDocumentPanel(this);            }            viewport.addPagePanelListener(new PagePanelListener() {                public void pageUpdated(PagePanelEvent event) {                    if (event.getType()=="redrawn") {                        viewport.removePagePanelListener(this);                        if (viewer!=null) {                            raiseDocumentPanelEvent(DocumentPanelEvent.createActivated(DocumentPanel.this));                        }                        raiseDocumentPanelEvent(DocumentPanelEvent.createLoaded(DocumentPanel.this));                    }                }            });            viewport.setDocumentPanel(this);            validate();            File file = (File)getClientProperty("file");            getJSManager().runEventDocOpen(this, file==null ? null : file.getName());            if (!initialpageset) {                setPage(pdf.getPage(0), 0, 0, 1);            }            viewport.requestFocusInWindow();        }        repaint();    }    //-----------------------------------------------------------------------------    // Controlling the view    /**     * Get the PDFParser being used to parse this PDF.     */    public PDFParser getParser() {        return parser;    }    /**     * Return the PDF currently being displayed by this <code>DocumentPanel</code>     */    public PDF getPDF() {        return pdf;    }    /**     * Return the PDFPage currently being displayed by the {@link DocumentViewport}.     * If no PDF is set or the first page is still being rendered, this method will return     * <code>null</code>.     */    public PDFPage getPage() {        return getViewport().getPage();    }    /**     * Set the page being displayed. A shortcut for <code>setPage(getPDF().getPage(i))</code>.     */    public void setPageNumber(int i) {        setPage(getPDF().getPage(i));    }    /**     * Return the pagenumber of the currently displayed page starting at 0, or -1 if no     * page is being displayed.     */    public int getPageNumber() {        PDFPage page = getPage();        return page==null ? -1 : page.getPageNumber()-1;    }    /**     * Return the current zoom level. A value of 1 means the document is being displayed     * at it's actual size, 0.5 means 50% and so on.     */    public float getZoom() {        return getViewport().getZoom();    }    /**     * Set the current zoom level     * @param zoom the zoom level     */    public void setZoom(float zoom) {        getViewport().setZoom(zoom);    }    /**     * Set the page to display in the {@link DocumentViewport}. The page is displayed     * at it's top-left and at the current zoom level.     * @param page the page     */    public void setPage(PDFPage page) {        setPage(page, 0, 0, getZoom());    }    /**     * Set the page to display in the {@link DocumentViewport}. The page is displayed     * at the co-ordinates supplied and at the specified zoom level.     * @param page the page     * @param x the left-most position of the page to display, in units relative to {@link PagePanel#getFullPageView}     * @param y the top-most position of the page to display, in units relative to {@link PagePanel#getFullPageView}     * @param zoom the zoom level     */    public void setPage(PDFPage page, float x, float y, float zoom) {        initialpageset = true;        getViewport().setPage(page, x, y, zoom);    }    /**     * Redraw the specified object. This method passes the object to the {@link SidePanel#redraw}     * and {@link DocumentViewport#redraw} methods, and should be called when the PDF has been     * updated somehow - ie a page or annotation has been altered.     * param o the Object that has been altered - typically a {@link PDFPage} or {@link PDFAnnotation}     */    public void redraw(Object o) {        if (o instanceof FormElement) {            for (Iterator i = ((FormElement)o).getAnnotations().iterator();i.hasNext();) {                redraw(i.next());            }        } else {            for (Iterator i = panels.values().iterator();i.hasNext();) {                ((SidePanel)i.next()).redraw(o);            }            getViewport().redraw(o);        }    }    //-----------------------------------------------------------------------------    // Other document actions    /**     * Display a Print dialog for printing this document, or if a {@link PrintService} is     * specified, print directly to that service without displaying a dialog.     * @param service the PrintService to print to. If this value is <code>null</code>     * a dialog will be displayed allowing the selection of a service.     * @param atts the print attributes - may be set to an AttributeSet to control the     * printing, or <code>null</code> to use the default.     */    public void print(PrintService service, PrintRequestAttributeSet atts) throws PrintException, PrinterException {        if (pdf==null) throw new NullPointerException("Document is null");        if (atts==null) {            atts = new HashPrintRequestAttributeSet();        }        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;        if (service==null) {            PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, atts);            if (services.length>0) {                PDFPage page = getPage();                if (atts.get(MediaSize.class)==null) {                    try {                        float w = page.getWidth()/72f;                        float h = page.getHeight()/72f;                        if (h>w) {                            atts.add(MediaSize.findMedia(w, h, Size2DSyntax.INCH));                        } else {                            atts.add(MediaSize.findMedia(h, w, Size2DSyntax.INCH));                            atts.add(OrientationRequested.LANDSCAPE);                        }                    } catch (Exception e) {}                }                if (atts.get(Sides.class)==null && pdf.getOption("print.duplex")!=null) {                    String s = (String)pdf.getOption("print.duplex");                    if ("DuplexFlipShortEdge".equals(s)) {                        atts.add(Sides.TWO_SIDED_SHORT_EDGE);                    } else if ("DuplexFlipLongEdge".equals(s)) {                        atts.add(Sides.TWO_SIDED_LONG_EDGE);                    }                }                if (atts.get(PageRanges.class)==null) {                    List l = (List)pdf.getOption("print.pagerange");                    if (l!=null) {                        int[][] x = new int[l.size()][];                        for (int i=0;i<l.size();i++) {                            x[i] = new int[] { ((PDFPage)l.get(i)).getPageNumber() };                        }                        atts.add(new PageRanges(x));                    }                }                if (atts.get(Copies.class)==null && pdf.getOption("print.numcopies")!=null) {                    atts.add(new Copies(((Integer)pdf.getOption("print.numcopies")).intValue()));                }                service =  ServiceUI.printDialog(null, 50, 50, services, service, flavor, atts);            } else {                JOptionPane.showMessageDialog(this, SuperJOptionPane.getLocalizedString("NoPrinters"), SuperJOptionPane.getLocalizedString("Alert"), JOptionPane.WARNING_MESSAGE);            }        }        if (service!=null) {            if (atts.get(DocumentName.class)==null) {                try {                    String title = pdf.getInfo("Title");                    if (title!=null) atts.add(new DocumentName(title, Locale.getDefault()));                } catch (ClassCastException e) {                }            }            final PrinterJob job = PrinterJob.getPrinterJob();            job.setPrintService(service);             job.setPageable(new Pageable() {                public int getNumberOfPages() {                    return parser.getNumberOfPages();                }                public Printable getPrintable(int pagenumber) {                    return parser.getPrintable(pagenumber);                }                public PageFormat getPageFormat(int pagenumber) {                    PageFormat format = parser.getPageFormat(pagenumber);                    Paper paper = job.defaultPage(format).getPaper();                    paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());                    format.setPaper(paper);                    return format;                }            });            getJSManager().runEventDocWillPrint(this);            job.print(atts);            // Technically we should be printing with a javax.print.SimpleDoc            // and run this event on the print completed event. However we            // dropped SimpleDoc for PrinterJob in 1.17, for something to            // do with landscape or odd media sizes as I recall. Double            // check this before implementing.            getJSManager().runEventDocDidPrint(this);        }    }    /*    public static void main(final String args[]) throws Exception {        final PDF pdf = new PDF(new PDFReader(new java.io.File(args[0])));        final DocumentPanel panel = new DocumentPanel();        panel.addAnnotationComponentFactory(org.faceless.pdf2.viewer2.feature.FormTextWidgetFactory.getInstance());        SwingUtilities.invokeLater(new Runnable() {            public void run() {                JFrame frame = new JFrame("BFO");                frame.getContentPane().add("Center", panel);                frame.pack();                frame.setSize(300, 300);                frame.setVisible(true);                panel.setPDF(pdf);            }        });    }    */}

⌨️ 快捷键说明

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