⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pdfviewport.java

📁 Java生成PDF Java生成PDF Java生成PDF
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
    /**     * Sets the zoom level of the viewport, in dots per inch.     * @param dpi how many dots per inch to view the page at     * @throws IllegalArgumentException if the DPI is <= 0     */    public void setDPI(double dpi) {        setPageNumber(pagenum, x1, y1, dpi);    }    /**     * Sets the view co-ordinates that appear in the upper left hand corner     * of the viewport, and the dots per inch of the display area.     *     * @param x the X co-ordinate of the upper-left hand corner of the viewport, in points     * @param y the Y co-ordinate of the upper-left hand corner of the viewport, in points     * @param dpi how many dots per inch to view the page. A value of 72 gives in 1 point     * per pixel. Must be > 0 or an {@link IllegalArgumentException} is thrown.     *     */    public void setViewPosition(double x, double y, double dpi) {        setPageNumber(pagenum, x, y, dpi);    }    /**     * Returns the page number of the current {@link PDFPage} being displayed in the viewport.     * @return the page number of the page currently displayed     */    public int getPageNumber() {        return pagenum;    }    /**     * Returns the view coordinates that appear in the upper left hand corner     * of the viewport, or 0,0 if there's no view.     */    public Point2D getViewPosition() {        return new Point2D.Double(x1, y1);    }    /**     * Returns the dots per inch of the viewport's display area, as set by {link #setDPI}     *     * @return the dots per inch of the display area.     */    public double getDPI() {        return dpi;    }    /**     * Returns the width of the current {@link PDFPage} in points, rounded to the     * nearest integer.  Returns 0 if no document has been set.     *     * @return the current width of the page in points     */    int getPageWidth() {        return (int)pagewidth;    }    /**     * Returns the height of the current {@link PDFPage} in points, rounded to the     * nearest integer.  Returns 0 if no document has been set.     *     * @return the current height of the page in points     */    int getPageHeight() {        return (int)pageheight;    }    /**     * Convert the viewport's PDF to a TIFF image using the specified ColorModel     * and dots per inch. The PDF is re-rendered in another thread, by calling     * {@link PDFParser#writeAsTIFF}.     *     * @param out The OutputStream to write the TIFF to.     * @param cm the ColorModel to use to render the images     * @throws NullPointerException if no document as been set     *     * @see PDFParser#writeAsTIFF     */    public void writeAsTIFF(OutputStream out, int dpi, ColorModel cm) {        if (pdf==null) {            throw new NullPointerException("Document is null");        }        final OutputStream o = out;        final int d = dpi;        final ColorModel c = cm;        new Thread () {            public void run() {                try {                    parser.writeAsTIFF(o, d, c);                    o.close();                } catch (IOException io) {                    ErrorInfo.displayThrowable(io, "TIFF Export Error", PDFViewport.this);                }                // notify observers                Iterator iterator = observers.iterator();                while (iterator.hasNext()) {                    ((ViewportObserver) iterator.next()).writeAsTIFFComplete();                }            }        }.start();    }    /**     * Repaint the component.     */    protected void paintComponent(Graphics g) {        super.paintComponent(g);        g.setColor(Color.GRAY);        g.fillRect(0, 0, getWidth(), getHeight());        if (pageImage != null) {            int w = pageImage.getWidth(this);            int h = pageImage.getHeight(this);            int x = w < getWidth() ? (getWidth() - w) / 2 : 0;            int y = h < getHeight() ? (getHeight() - h) / 2 : 0;            // Drop shadow            g.setColor(Color.BLACK);            g.fillRect(x+3, y+3, w, h);            // Image            Shape clip = g.getClip();            g.clipRect(x, y, w, h);            g.drawImage(pageImage, x, y, this);            // Transform the canvas, call the annotateComponent            // method and then untransform it.            AffineTransform f = ((Graphics2D)g).getTransform();            AffineTransform newf = new AffineTransform(dpi/SCREENDPI, 0, 0, -dpi/SCREENDPI,                                                        -x1*dpi/SCREENDPI + x,                                                        (pageheight-y1)*dpi/SCREENDPI + y);            ((Graphics2D)g).transform(newf);            annotateComponent((Graphics2D)g);            ((Graphics2D)g).setTransform(f);            g.setClip(clip);            g.setColor(Color.BLACK);            g.drawRect(x, y, w, h);        }    }    /**     * This method is called whenever the PDF page is redrawn. By default it     * does nothing, but it can be overridden by subclasses to annotate the     * canvas. The co-ordinate system in use when this method is called is     * the PDF co-ordinate system, so (0,0) is the bottom left of the page     * and the DPI, scroll position etc. of this PDFViewport can be ignored.     * </p><p>     * More advanced applications can use the tranformation applied to the     * Graphics2D object to reposition any components this Viewport may have.     * The following code would get you started:     * <pre class="example">     *  AffineTransform tran = g.getTransform();     *  final float scalex = (float)tran.getScaleX();     *  final float scaley = (float)tran.getScaleY();     *  final float dx = (float)tran.getTranslateX();     *  final float dy = (float)tran.getTranslateY();     *     *  Component[] comps = getComponents();     *  for (int i=0;i&lt;comps.length;i++) {     *      Rectangle r = getComponentPosition(comps[i]);     *      float x = r.x*scalex + dx;     *      float y = r.y*scaley + dy;     *      float w = r.width * scalex;     *      float h = r.height * Math.abs(scaley);     *      comps[i].setBounds((int)x, (int)y, (int)w, (int)h);     *  }     * </pre>     *     * @param g the Graphics2D object containing the just-rendered page.     * @since 2.7.1     */    protected void annotateComponent(Graphics2D g) {    }    /**     * Adds a {@link ViewportObserver} to be notified of viewport events.     * @param observer the {@link ViewportObserver} to be added     */    public void addObserver(PDFViewport.ViewportObserver observer) {        observers.add(observer);    }    /**     * Removes a {@link ViewportObserver}.     * @param observer the {@link ViewportObserver} to be removed     */    public void removeObserver(PDFViewport.ViewportObserver observer) {        observers.remove(observer);    }    /**     * Displays a print dialog for printing any pages from the document in the viewport. Print     * a single page or a range of pages.     *     * @throws NullPointerException if no document has been set     * @see #setDocument(PDF)     */    public void print() {        if (pdf==null) throw new NullPointerException("Document is null");        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;        PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null);        if (services.length > 0) {            try {                PrinterJob job = PrinterJob.getPrinterJob();                job.setPageable(parser);                if (pdf.getInfo("Title")!=null) {                    job.setJobName(pdf.getInfo("Title"));                } else {                    job.setJobName("BFO PDF");                }                if(job.printDialog()) {                    job.print();                }            } catch (PrinterException e) {                e.printStackTrace();            }        } else {            JOptionPane.showMessageDialog(this, "No printers are installed","Print Warning",JOptionPane.WARNING_MESSAGE);        }    }    class PageWorker extends SwingWorker {        private boolean interrupted;        final int pagenum;        final float dpi, x1, y1, x2, y2, pageheight;        PageWorker(int pagenum, float x1, float y1, float x2, float y2, float dpi, float pageheight) {            this.pageheight = pageheight;            this.pagenum = pagenum;            this.dpi = dpi;            this.x1 = x1;            this.x2 = x2;            this.y1 = y1;            this.y2 = y2;        }        /**         * Here we recreate pageImage.         *          * 1. If the zoom level and image size are such that we can render the         *    entire page in a "reasonable" size, we render the entire page to         *    "fullImage" and then createa a subImage of that as "pageImage".         *    This is faster than it sounds as the raster is not copied.         *         * 2. If not, we render only the portion we can to "pageImage"         */        public Object construct() {            try {                if (!isFullImageOK()) {                    pageImage = painters[pagenum].getSubImage(pageleft+x1, pagebottom+pageheight-y2, pageleft+x2, pagebottom+pageheight-y1, dpi, colormodel);                } else {                    if (updateImage) {                        // page or dpi changed so render full page                        fullImage = painters[pagenum].getSubImage(pageleft, pagebottom, pageleft+pagewidth, pagebottom+pageheight, dpi, colormodel);                    }                    if (fullImage != null) {                        float x = x1 * dpi / SCREENDPI;                        float y = y1 * dpi / SCREENDPI;                        float w = fullImage.getWidth() - x;                        float h = fullImage.getHeight() - y;//                        System.out.println("fw="+fullImage.getWidth()+" fh="+fullImage.getHeight()+" x="+x+" y="+y+" w="+w+" h="+h);                        pageImage = fullImage.getSubimage((int)x, (int)y, (int)w, (int)h);                    }               }            } catch (Exception e) {                fullImage = null;                pageImage = null;                ErrorInfo.displayThrowable(e, "Page Painter Error", PDFViewport.this);            }            return null;        }        public void finished() {            if (task.isInterrupted()) {                task = null;                setViewPosition(PDFViewport.this.x1, PDFViewport.this.y1);            } else {                task = null;                updateImage = false;                repaint();            }        }        public void interrupt() {            interrupted = true;

⌨️ 快捷键说明

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