Utilizzo di IText per scrivere file pdf da classe Java

Attraverso questo articolo vediamo alcune semplici classi che utilizzano una libreria opensource, IText, attraverso la quale gestiremo la creazione di file pdf

Bentornati,
questo articolo continua l’ultimo da me inserito relativo alla creazione di interfacce swing tramite classe generica Java

Creazione Form in Java Swing tramite classe generica

Continueremo su questo passo, quindi utilizzerò la classe generica per creare questa volta una form che permette di registrare i dati immessi in un file .pdf. Per la registrazione dei dati su pdf utilizzeremo una libreria eccezionale, di semplice utilizzo e che permette la creazione di pdf “on the fly”:  IText, scaricabile dal sito http://www.lowagie.com/iText/

Bene iniziamo con il codice:
Creo una classe generica per una form di memorizzazione dati RDBMS (datasource, jdbcDriver, dbURL…)

1) Classe generica:

public class GenericInteface extends JPanel {

	/*
	 * Etichette per la GUI
	 */
	protected final static String names[] = { 
		"Datasource", "JDBC Driver", "DB URL", 
		"Username", "Password" };

	/*
	 * Componenti GUI, dichiarati protected 
	 * per l'accesso da sottoclassi
	 */
	protected JLabel labels[];
	public JTextField fields[];
	protected JButton doTask1, doTask2, doTask3, doTask4, doTask5, doTask6;
	protected JPanel innerPanelCenter, innerPanelSouth, innerPanelNothern,
			innerPanelEast;

	/*
	 * Numero dei campi di testo della GUI
	 */
	public int size;

	/*
	 * Costanti che rappresentano i campi di testo della GUI
	 */
	public static final int GENERIC1 = 0, GENERIC2 = 1, GENERIC3 = 2,
			GENERIC4 = 3, GENERIC5 = 4;

	/*
	 * Imposta la GUI. La dimensione dell'argomento 
	 * del costruttore determina il numero di righe dei componenti GUI
	 */
	public GenericInteface(int mySize) {
		size = mySize;
		labels = new JLabel[size];
		fields = new JTextField[size];

		/*
		 * Crea etichette
		 */
		for (int count = 0; count < labels.length; count++) {
			labels[count] = new JLabel(names[count]);
		}

		/*
		 * Crea campi di testo
		 */
		for (int count = 0; count < fields.length; count++) {
			fields[count] = new JTextField();
		}

		/*
		 * Crea il pannello CENTRALE per disporre testi ed etichette
		 */
		innerPanelCenter = new JPanel();
		// altezza x larghezza
		innerPanelCenter.setLayout(new GridLayout(size, 2)); 

		/*
		 * Attacca etichette e campi di testo a innerPanelCenter
		 */
		for (int count = 0; count < size; count++) {
			innerPanelCenter.add(labels[count]);
			innerPanelCenter.add(fields[count]);
		}

		/*
		 * Crea pulsanti generici senza etichette e gestori di eventi
		 */
		doTask1 = new JButton();
		doTask2 = new JButton();
		doTask3 = new JButton();
		doTask4 = new JButton();
		doTask5 = new JButton();
		doTask6 = new JButton();
		/*
		 * Crea il pannello SUD per disporre i pulsanti e li attacca
		 */
		innerPanelSouth = new JPanel();
		innerPanelSouth.add(doTask1);
		innerPanelSouth.add(doTask2);
		innerPanelSouth.add(doTask3);
		innerPanelSouth.add(doTask4);
		innerPanelSouth.add(doTask5);
		innerPanelSouth.add(doTask6);
		/*
		 * Creo un oggetto img di tipo Image
		 */
		Image img;

		Toolkit tk = Toolkit.getDefaultToolkit();
		img = tk.getImage("C:/imagei.jpg"); // un esempio
		ImageIcon ic = new ImageIcon(img);
		JLabel nothern2 = new JLabel(ic);

		/*
		 * Crea il pannello NORD per disporre la JLabel
		 * 
		 */
		innerPanelNothern = new JPanel();
		innerPanelNothern.add(nothern2);

		/*
		 * Imposta il layout del contenitore e attacca i pannelli
		 */
		setLayout(new BorderLayout());
		add(innerPanelNothern, BorderLayout.NORTH);
		add(innerPanelCenter, BorderLayout.CENTER);
		add(innerPanelSouth, BorderLayout.SOUTH);

		validate();
	}

	/*
	 * Metodi get e set
	 */
	public JButton getDoTask1() {
		return doTask1;
	}

	public JButton getDoTask2() {
		return doTask2;
	}

	public JTextField[] getFields() {
		return fields;
	}

	public JButton getDoTask4() {
		return doTask4;
	}

	public JButton getDoTask3() {
		return doTask3;
	}

	public JButton getDoTask5() {
		return doTask5;
	}

	public JButton getDoTask6() {
		return doTask6;
	}

	public void clearFields() {
		for (int count = 0; count < size; count++) {
			fields[count].setText("");
		}
	}

	// imposta i valori dei campi di testo
	public void setFieldValues(String strings[])
			throws IllegalArgumentException {
		if (strings.length != size)
			throw new IllegalArgumentException("Array out of bounds");

		for (int count = 0; count < size; count++)
			fields[count].setText(strings[count]);
	}

	// ottiene un array di stringhe 
	// con il contenuto dei campi di testo
	public String[] getFieldValues() {
		String values[] = new String[size];

		for (int count = 0; count < size; count++)
			values[count] = fields[count].getText();

		return values;
	}
}

2) Form :

public class RegisterInterface extends JFrame {

	private GenericInteface userInterface;
	private JButton registerButton, clearButton, connectionButton,
			comeBackButton, openFileButton, readFileButton;
	String datasource = "";
	String jdbcDriver = "";
	String dbURL = "";
	String username = "";
	String password = "";

	/*
	 * Imposta la GUI
	 */
	public RegisterInterface() {
		super("Form di Registrazione RDBMS");

		/*
		 * Aggiungo l'Interfaccia generica e la centro allo schermo creando
		 * l'oggetto userInterface e impostando i campi nella form a 2
		 */
		userInterface = new GenericInteface(5);
		getContentPane().add(userInterface, BorderLayout.CENTER);

		/*
		 * Configuro il pulsante doTask1
		 */
		registerButton = userInterface.getDoTask1();
		registerButton.setText("Registra");
		registerButton.setToolTipText("Registra RDBMS");
		registerButton.setEnabled(true);

		/*
		 * Configuro il pulsante doTask2
		 */
		clearButton = userInterface.getDoTask2();
		clearButton.setText("Clear");
		clearButton.setToolTipText("Cancella i campi");

		/*
		 * Configuro il pulsante doTask3
		 */
		connectionButton = userInterface.getDoTask3();
		connectionButton.setText("Try Connection");
		connectionButton.setToolTipText("Testa la connessione al db");

		/*
		 * Configuro il pulsante doTask4
		 */
		comeBackButton = userInterface.getDoTask4();
		comeBackButton.setText("Torna");
		comeBackButton.setToolTipText("Torna");

		/*
		 * Configuro il pulsante doTask5
		 */
		openFileButton = userInterface.getDoTask5();
		openFileButton.setText("Aggiungi Datasource");
		openFileButton.setToolTipText("Aggiungi Datasource su file");

		/*
		 * Configuro il pulsante doTask6
		 */
		readFileButton = userInterface.getDoTask6();
		readFileButton.setText("Datasource Presenti");

		/*
		 * Chiamata ad ActionListener per il primo bottone
		 */
		openFileButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {

			}
		}); // Fine chiamata ad ActionListener per il primo bottone

		/*
		 * Chiamata ad ActionListener per il primo bottone
		 */
		readFileButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {

			}
		}); // Fine chiamata ad ActionListener per il primo bottone

		/*
		 * Chiamata ad ActionListener che chiama il metodo "registra della
		 * classe InsertQuery" per il primo bottone
		 */
		registerButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				datasource = userInterface.fields[0].getText();
				jdbcDriver = userInterface.fields[1].getText();
				dbURL = userInterface.fields[2].getText();
				username = userInterface.fields[3].getText();
				password = userInterface.fields[4].getText();

				SimpleRegistrationForm form = new SimpleRegistrationForm();
				form.scrivi(datasource, jdbcDriver, dbURL, username, password);

			}
		}); // Fine chiamata ad ActionListener per il primo bottone

		/*
		 * ClearFields
		 */
		clearButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				userInterface.clearFields();
			}
		}); // Fine chiamata ad ActionListener per il secondo bottone

		/*
		 * Chiamata ad ActionListener che si connnette al db per il terzo
		 * bottone
		 */
		connectionButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
			}
		}); // Fine chiamata ad ActionListener per il terzo bottone

		/*
		 * ComeBackButton
		 */
		comeBackButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
			}
		}); // Fine chiamata ad ActionListener per il quarto bottone

		/*
		 * Registra ascoltatore per chiusura finestra
		 */
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent event) {
				System.exit(1);
			}
		}); // Fine chiamata a WindowListener

		/*
		 * Regolazioni Contenitore
		 */
		setSize(700, 235); // Larghezza x Altezza
		setVisible(true);
		setResizable(false);
		setLocation(250, 300); // Centro il contenitore allo schermo
	}

	public static void main(String[] args) {
		new RegisterInterface();
	}

}

3) Classe Java con IText

public class SimpleRegistrationForm implements PdfPCellEvent {

	private PdfWriter writer;

	private String fieldname = "NoName";

	public String datasource;
	public String jdbcDriver;
	public String dbURL;
	public String username;
	public String password;

	public SimpleRegistrationForm(PdfWriter writer) {
		this.writer = writer;
	}

	public SimpleRegistrationForm(PdfWriter writer, String fieldname) {
		this.writer = writer;
		this.fieldname = fieldname;
	}

	public SimpleRegistrationForm(){
	}

	public void cellLayout(PdfPCell cell, Rectangle position,
			PdfContentByte[] canvases) {
		TextField tf = new TextField(writer, position, fieldname);
		tf.setFontSize(12);
		try {
			PdfFormField field = tf.getTextField();
			writer.addAnnotation(field);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	public void scrivi(String datasource,
				       String jdbcDriver,
				       String dbURL,
				       String username,
				       String password){

		// step 1  crea il ducomento
		Document document = new Document(PageSize.A4, 50, 50, 50, 50);
		try {
			// step 2 nome del documento
			PdfWriter writer = PdfWriter.getInstance(document, 
                        new FileOutputStream(datasource+".pdf"));

			// step 3 apre il documento
			document.open();

			//aggiungo un logo
			Image jpeg = Image.getInstance("image.jpg");
			jpeg.setAbsolutePosition(20f, 777f);
			jpeg.scalePercent(70);
			document.add(jpeg);

			// step 4 crea la tabella
			PdfPTable table = new PdfPTable(2);
			PdfPCell cell;
			table.getDefaultCell().setPadding(5f);

			table.addCell("Datasource:");
			cell = new PdfPCell();
			cell.setCellEvent(new SimpleRegistrationForm(writer, "datasource"));  
                        //rende editabile il campo
			cell.setPhrase(new Phrase(datasource));
			table.addCell(cell);

			table.addCell("JdbcDriver:");
			cell = new PdfPCell();
			cell.setCellEvent(new SimpleRegistrationForm(writer, "jdbcDriver"));
			cell.setPhrase(new Phrase(jdbcDriver));
			table.addCell(cell);

			table.addCell("dbURL:");
			cell = new PdfPCell();
			cell.setCellEvent(new SimpleRegistrationForm(writer, "dbURL"));
			cell.setPhrase(new Phrase(dbURL));
			table.addCell(cell);

			table.addCell("Username:");
			cell = new PdfPCell();
			cell.setCellEvent(new SimpleRegistrationForm(writer, "username"));
			cell.setPhrase(new Phrase(username));
			table.addCell(cell);

			table.addCell("Password:");
			cell = new PdfPCell();
			cell.setCellEvent(new SimpleRegistrationForm(writer, "password"));
			cell.setPhrase(new Phrase(password));
			table.addCell(cell);
			document.add(table);

		} catch (DocumentException de) {
			System.err.println(de.getMessage());
		} catch (IOException ioe) {
			System.err.println(ioe.getMessage());
		}
		// step 5 chiude il documento
		document.close();
	}
}

Ricordatevi di aggiungere al Classpath il .jar IText ed eseguite la main class e buon lavoro con IText

 

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.