Visualizzazione dei risultati da 1 a 7 su 7
  1. #1

    Pdf Rendere per visualizzare più pagine [aiuto per favore]

    Salve ragazzi, avrei una questione da proporvi.

    Sono riuscito a caricare un file PDF nel mio programma attraverso la librerie PDF-Renderer.

    Preavviso che per alcuni motivi devo assolutamente utilizzare questa.

    Devo visualizzare il file pdf in una componente del tipo JInternalFrame.

    Fin qui nulla di complicato e ci sono riuscito.

    Adesso però come voi ben sapete un file pdf può avere più pagine mica per forza solo una.

    Con il codice di esempio del sito : https://pdf-renderer.dev.java.net/examples.html

    sono riuscito a far visualizzare la prima pagina di qualsiasi documento pdf.

    Adesso dvo dare la possibilità di poter visualizzare anche le altre pagine ho apportato alcune modifiche ed ho inserito un pulsante per andare in avanti così come noi facciamo con acrobat reader.

    Allora se visualizzo la nuova pagine nel JInternalFrame che contiene la prima pagine non visualizzo nulla Se creo un nuovo JInternalFrame mi viene visualizzata correttamente, potete ovviare a questo problema??

    Intanto posto il codice della mia classe:

    codice:
    public class ImageMain {
    public static int numeroPagine;
    public static int i;
        public static void setup() throws IOException {
        	i=1;
        	final JFrame frame2 = new JFrame("PDF Test");
            frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //load a pdf from a byte buffer
            
            final JInternalFrame frame = new JInternalFrame("PDF Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            final File file = new File("c:/m.pdf");
            final RandomAccessFile raf = new RandomAccessFile(file, "r");
            final FileChannel channel = raf.getChannel();
            final ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            final PDFFile pdffile = new PDFFile(buf);
            numeroPagine = pdffile.getNumPages();
          
            // draw the first page to an image
            PDFPage page = pdffile.getPage(0);
            final BufferedImage img = new BufferedImage((int)page.getBBox().getWidth(),
                    (int)page.getBBox().getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = img.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //get the width and height for the doc at the default zoom 
            Rectangle rect = new Rectangle(0,0,
                    (int)page.getBBox().getWidth(),
                    (int)page.getBBox().getHeight());
            try{
            //generate the image
            PDFRenderer renderer = new PDFRenderer(page, g2, 
            	    new Rectangle(0, 0, (int)page.getBBox().getWidth(),
                            (int)page.getBBox().getHeight()), null, Color.white);
            	page.waitForFinish();
            	renderer.run();
            }catch(Exception e){}
            
            final JButton Botton = new JButton("Avanti");
            Botton.setSize( Botton.getPreferredSize() );
            frame2.add(Botton);
            Botton.addActionListener( new ActionListener() {
                public void actionPerformed( ActionEvent e ) {
                	if(i>numeroPagine){
                	   Botton.setEnabled(false);	
                	}
                	else{
                		try{
                		i++;
                		
                		PDFPage page2 = pdffile.getPage(i);
                		
                		BufferedImage img = new BufferedImage((int)page2.getBBox().getWidth(),
                                (int)page2.getBBox().getHeight(), BufferedImage.TYPE_INT_ARGB);
                		 Graphics2D g2 = img.createGraphics();
                	        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                	        //get the width and height for the doc at the default zoom 
                	        Rectangle rect = new Rectangle(0,0,
                	                (int)page2.getBBox().getWidth(),
                	                (int)page2.getBBox().getHeight());
                	        
                	            //generate the image
                	            PDFRenderer renderer = new PDFRenderer(page2, g2, 
                	            	    new Rectangle(0, 0, (int)page2.getBBox().getWidth(),
                	                            (int)page2.getBBox().getHeight()), null, Color.white);
                	            	page2.waitForFinish();
                	            	renderer.run();
                	            	
                	           	JFrame framed = new JFrame("DDD");
                      	           
                        	        
                    	           JInternalFrame frame3 = new JInternalFrame("PDFTEST"); 
                    	           frame3.add(new JLabel(new ImageIcon(img)));
                    	            frame3.pack();
                    	            frame3.setVisible(true);
                    	            framed.add(frame3);
                    	            framed.pack();
                    	           framed.setVisible(true);
                    	            System.out.println("sono arrivato");
                	            }catch(Exception r){}
                	            System.out.println("sono arrivato");
                	            //frame2.removeAll();
                	           // frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                	          // frame.removeAll();
                	         //  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                	          
                	}
                }
                });
            //show the image in a frame
            
            frame.add(new JLabel(new ImageIcon(img))); 
            frame.pack();
            frame.setVisible(true);
            
           
            frame2.add(frame);
            frame2.pack();
            frame2.setVisible(true);
        }
    
        public static void main(final String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        ImageMain.setup();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }
    }
    
    Con questo codice io apro ogni volta un nuovo Frame e un nuovo JInternalFrame ma io devo fare in modo che questo avvenga tutto in uno.
    
    Saluti Michele

  2. #2
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    mancherà un validate() da qualche parte quando vai a disegnare la nuova pagina.
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  3. #3
    cioè, potresti spiegarti meglio?

    il codice così come l'ho inserito funziona perfettamente.

    Soltanto che ogni qual volta vado avanti mi apre un nuovo JFrame e JInternalFrame io invece voglio che il Jframe che io chiamo frame2 rimanga sempre tale e il JinternalFrame che io chiamo frame cambi, cioè ogni qual volta io premo il pulsante esso deve camibare immagine.

  4. #4
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    Ho ripreso direttamente l'esempio di codice dalla pagina ufficiale di PDFRenderer in quanto e rimaneggiato un attimo (in sostanza, ho splittato il metodo setup, aggiunto un costruttore esplicitamente dichiarato ed un listener)

    codice:
    import com.sun.pdfview.PDFFile;
    import com.sun.pdfview.PDFPage;
    import com.sun.pdfview.PagePanel;
    import java.io.*;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    /**
     * An example of using the PagePanel class to show PDFs. For more advanced
     * usage including navigation and zooming, look ad the
     * com.sun.pdfview.PDFViewer class.
     *
     * @author joshua.marinacci@sun.com
     */
    public class ViewTest extends JFrame {
    
        private class MyPageButtonListener implements ActionListener {
    
            public MyPageButtonListener() {            
                if (pg == 1) {
                    indietro.setEnabled(false);
                }
                if (pg == tot_pages) {
                    avanti.setEnabled(false);
                }
            }
    
            public void actionPerformed(ActionEvent ae) {                                    
                JButton src = (JButton)ae.getSource();
                if (src.equals(indietro)) {
                    pg--;
                    if (pg <= 1) {
                        indietro.setEnabled(false);
                    }                
                    avanti.setEnabled(true);
                    showPage(pg);
                }
                else {
                    pg++;
                    if (pg >= tot_pages) {
                        avanti.setEnabled(false);
                    }                
                    indietro.setEnabled(true);
                    showPage(pg);
                }
            }
        }
    
        private JButton avanti, indietro;
        private PagePanel panel;
        private PDFFile pdffile;
        private String path;
        private int pg, tot_pages;
    
        public ViewTest(String path, int pg) {
            super("Test PDF");
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.avanti = new JButton("Avanti");
            this.indietro = new JButton("Indietro");
            this.pg = pg;
            this.panel = new PagePanel();
            this.path = path;
    
            this.getContentPane().add(new JScrollPane(panel), BorderLayout.CENTER);
            JPanel northPanel = new JPanel(new GridLayout(1,2));
            northPanel.add(indietro);
            northPanel.add(avanti);
            this.getContentPane().add(northPanel, BorderLayout.NORTH);        
            this.setSize(800,800);
            this.setVisible(true);        
    
            try {
                this.setup(path);
                this.showPage(pg);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            indietro.addActionListener(new MyPageButtonListener());
            avanti.addActionListener(new MyPageButtonListener());
        }
    
        public void showPage(int pg) {
            PDFPage page = pdffile.getPage(pg);
            panel.showPage(page);
            panel.validate();
        }
    
        public void setup(String path) throws IOException {
            //set up the frame and panel    
            //load a pdf from a byte buffer
            File file = new File(path);
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            FileChannel channel = raf.getChannel();
            ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,
                0, channel.size());
            pdffile = new PDFFile(buf);
            tot_pages = pdffile.getNumPages();
        }
    
        public static void main(final String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {               
                        new ViewTest("tuo_file_pdf", 1);
                }
            });
        }
    }
    Mi sono accorto che pagina 0 o 1 sono la stessa cosa... allora per comodità parto da pagina 1. Presta solo attenzione al metodo showPage: è lì che viene usato validate.
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  5. #5
    Ciao grazie mille per il tuo prezioso suggerimento purtroppo però non credo mi possa essere utile il tuo codice poichè io devo visualizzare per forza l'immagine creata del pdf in un JInternalFrame e non in un JFrame o panel o altro.

  6. #6
    Ecco questo è il codice della mi classe se dai una occhiata nel codice.

    codice:
    import com.sun.pdfview.PDFFile;
    import com.sun.pdfview.PDFPage;
    import com.sun.pdfview.PDFRenderer;
    
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import javax.swing.*;
    
    /**
     * An example of drawing a PDF to an image.
     *
     * @author joshua.marinacci@sun.com
     */
    public class ImageMain {
    public static int numeroPagine;
    public static int i;
        public static void setup() throws IOException {
        	i=1;
        	final JFrame frame2 = new JFrame("PDF Test");
            frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //load a pdf from a byte buffer
            
            final JInternalFrame frame = new JInternalFrame("PDF Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            final File file = new File("c:/m.pdf");
            final RandomAccessFile raf = new RandomAccessFile(file, "r");
            final FileChannel channel = raf.getChannel();
            final ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            final PDFFile pdffile = new PDFFile(buf);
            numeroPagine = pdffile.getNumPages();
          
            // draw the first page to an image
            PDFPage page = pdffile.getPage(0);
            final BufferedImage img = new BufferedImage((int)page.getBBox().getWidth(),
                    (int)page.getBBox().getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = img.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //get the width and height for the doc at the default zoom 
            Rectangle rect = new Rectangle(0,0,
                    (int)page.getBBox().getWidth(),
                    (int)page.getBBox().getHeight());
            try{
            //generate the image
            PDFRenderer renderer = new PDFRenderer(page, g2, 
            	    new Rectangle(0, 0, (int)page.getBBox().getWidth(),
                            (int)page.getBBox().getHeight()), null, Color.white);
            	page.waitForFinish();
            	renderer.run();
            }catch(Exception e){}
            
            final JButton Botton = new JButton("Avanti");
            Botton.setSize( Botton.getPreferredSize() );
            frame2.add(Botton);
            Botton.addActionListener( new ActionListener() {
                public void actionPerformed( ActionEvent e ) {
                	if(i>numeroPagine){
                	   Botton.setEnabled(false);	
                	}
                	else{
                		try{
                		i++;
                		// File file = new File("c:/m.pdf");
                       //  RandomAccessFile raf = new RandomAccessFile(file, "r");
                     //  FileChannel channel = raf.getChannel();
                       // ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
                         //PDFFile pdffile = new PDFFile(buf);
                		PDFPage page2 = pdffile.getPage(i);
                		
                		BufferedImage img = new BufferedImage((int)page2.getBBox().getWidth(),
                                (int)page2.getBBox().getHeight(), BufferedImage.TYPE_INT_ARGB);
                		 Graphics2D g2 = img.createGraphics();
                	        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                	        //get the width and height for the doc at the default zoom 
                	        Rectangle rect = new Rectangle(0,0,
                	                (int)page2.getBBox().getWidth(),
                	                (int)page2.getBBox().getHeight());
                	        
                	            //generate the image
                	            PDFRenderer renderer = new PDFRenderer(page2, g2, 
                	            	    new Rectangle(0, 0, (int)page2.getBBox().getWidth(),
                	                            (int)page2.getBBox().getHeight()), null, Color.white);
                	            	page2.waitForFinish();
                	            	renderer.run();
                	            	
                	            	
                	            	frame.add(new JLabel(new ImageIcon(img)));
                	                frame.validate();
                	           	    
                	            }catch(Exception r){}
                	            System.out.println("sono arrivato");
                	            //frame2.removeAll();
                	           // frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                	          // frame.removeAll();
                	         //  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                	          
                	}
                }
                });
            //show the image in a frame
            
            frame.add(new JLabel(new ImageIcon(img))); 
            frame.pack();
            frame.setVisible(true);
            
           
            frame2.add(frame);
            frame2.pack();
            frame2.setVisible(true);
        }
    
        public static void main(final String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        ImageMain.setup();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            });
        }
    }
    Come si può notare la prima pagine viene caricata correttamente purtroppo cliccando sul pulsante avanti invece non compare nulla.
    Volevo sapere c'è qualche modo per poter aggiornare il contenuto di un oggetto di tipo JInternalFrame???

  7. #7
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    Sì, ho visto il tuo codice e secondo me ti stai complicando la vita.
    Il codice del primo esempio della pagina del progetto è più che sufficiente... ti basta solo mettere insieme la gestione degli internal frame con quel codice. Mi riferisco sempre al codice che ho postato sopra, modificato per utilizzare un JInternalFrame (con qualche commento...)

    codice:
    import com.sun.pdfview.PDFFile;
    import com.sun.pdfview.PDFPage;
    import com.sun.pdfview.PagePanel;
    import java.io.*;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    /**
     * An example of using the PagePanel class to show PDFs. For more advanced
     * usage including navigation and zooming, look ad the
     * com.sun.pdfview.PDFViewer class.
     *
     * @author joshua.marinacci@sun.com
     */
    public class ViewTest extends JFrame {
    
        private class MyPageButtonListener implements ActionListener {
    
            public MyPageButtonListener() {            
                if (pg == 1) {
                    indietro.setEnabled(false);
                }
                if (pg == tot_pages) {
                    avanti.setEnabled(false);
                }
            }
    
            public void actionPerformed(ActionEvent ae) {                                    
                JButton src = (JButton)ae.getSource();
                if (src.equals(indietro)) {
                    pg--;
                    if (pg <= 1) {
                        indietro.setEnabled(false);
                    }                
                    avanti.setEnabled(true);
                    showPage(pg);
                }
                else {
                    pg++;
                    if (pg >= tot_pages) {
                        avanti.setEnabled(false);
                    }                
                    indietro.setEnabled(true);
                    showPage(pg);
                }
            }
        }
    
        private JButton avanti, indietro;
        private PagePanel panel;
        private PDFFile pdffile;
        private String path;
        private int pg, tot_pages;
        private JInternalFrame iframe;
        private JDesktopPane desktop;
    
        public ViewTest(String path, int pg) {
            super("Test PDF");
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.avanti = new JButton("Avanti");
            this.indietro = new JButton("Indietro");
            this.pg = pg;
            this.panel = new PagePanel();
            this.path = path;
    
            //Creo un JDesktop pane per accogliere i JInternalFrame
            desktop  = new JDesktopPane();
            this.setContentPane(desktop);
    
            //Creo il JInternalFrame vero e proprio.
            iframe = new JInternalFrame("PDF File", true, true, true, true);
            iframe.setLayout(new BorderLayout());
            iframe.getContentPane().add(new JScrollPane(panel), BorderLayout.CENTER);
    
            //pannello bottoni
            JPanel northPanel = new JPanel(new GridLayout(1,2));
            northPanel.add(indietro);
            northPanel.add(avanti);
            iframe.getContentPane().add(northPanel, BorderLayout.NORTH);
            //dimensioni e posizione relativa del JInternalFrame
            iframe.setSize(400, 300);
            iframe.setLocation(50, 50);
            //rendiamo il JInternalFrame visibile e aggiungiamolo al JDestopPane
            iframe.setVisible(true);        
            desktop.add(iframe);
            
            this.setSize(800,800);        
            this.setVisible(true);        
    
            try {
                this.setup(path);
                this.showPage(pg);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            indietro.addActionListener(new MyPageButtonListener());
            avanti.addActionListener(new MyPageButtonListener());
                    
        }
    
        public void showPage(int pg) {
            PDFPage page = pdffile.getPage(pg);
            panel.showPage(page);
            panel.validate();
        }
    
        public void setup(String path) throws IOException {
            //set up the frame and panel    
            //load a pdf from a byte buffer
            File file = new File(path);
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            FileChannel channel = raf.getChannel();
            ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,
                0, channel.size());
            pdffile = new PDFFile(buf);
            tot_pages = pdffile.getNumPages();
        }
    
        public static void main(final String[] args) {        
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {               
                        new ViewTest("tuo_pdf.pdf", 1);
                }
            });
        }
    }
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.