Exemple de création de tableau avec itext en Java
Télécharger la librairie itext5 (disponible dans \\prof\ressources)
Ajouter le fichier itextpdf-5.4.0.jar dans la librairie du projet.
PDFTableExample.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
/**
* Cette classe permet de créer un fichier pdf en
* utilisant la librairie iText.
*/
public class PDFTableExample {
public static void main(String args[]){
try {
//Création de l'instance de Document.
Document document = new Document();
//Création d'une instance de OutputStream.
OutputStream outputStream = new FileOutputStream(new File("D:\\TestTableFile.pdf"));
//Création de l'instance PDFWriter
PdfWriter.getInstance(document, outputStream);
//Ouverture du document.
document.open();
//Création du tableau. Ici 4 colonnes
PdfPTable pdfPTable = new PdfPTable(4);
//Création des cellules du tableau
PdfPCell pdfPCell1 = new PdfPCell(new Paragraph("Cell 1"));
PdfPCell pdfPCell2 = new PdfPCell(new Paragraph("Cell 2"));
PdfPCell pdfPCell3 = new PdfPCell(new Paragraph("Cell 3"));
PdfPCell pdfPCell4 = new PdfPCell(new Paragraph("Cell 4"));
//Ajout des cellules dans le tableau
pdfPTable.addCell(pdfPCell1);
pdfPTable.addCell(pdfPCell2);
pdfPTable.addCell(pdfPCell3);
pdfPTable.addCell(pdfPCell4);
//Ajout du tableau dans le document
document.add(pdfPTable);
//Fermeture du document et du outputStream.
document.close();
outputStream.close();
System.out.println("Pdf créé avec succès !");
} catch (Exception e) {
e.printStackTrace();
}
}
}