17/06/2008

Création d'un fichier PDF par API, grace à iTextSharp

iText# (iTextSharp) est le portage de la librairie open source iText écrite en Java en C#.
Cette librairie permet de générer des fichiers PDF par API.

Le site d’iTextSharp : http://sourceforge.net/projects/itextsharp/
Un tutorial en français : http://itext.ugent.be/articles/iTextSharp.doc
Le très bon site de tutorial et astuces (anglais) : http://itextdocs.lowagie.com/tutorial/
Il existe un livre, qui de faite est la bible :
http://www.amazon.com/dp/1932394796?tag=itisacatalofwebp&camp=14573&creative=327641&linkCode=as1&creativeASIN=1932394796&adid=1GSTB23N4QZGGGNKY5MD&

Un exemple simple de mise en œuvre.

using System;
using System.IO;
using iTextSharp ;
using iTextSharp.text ;
using iTextSharp.text.pdf ;

namespace TestiText
{
class Program
{
static void Main(string[] args)
{
Document pdfDoc = new Document();

try
{
PdfWriter.GetInstance (pdfDoc, new FileStream("fichier.pdf", FileMode.Create));
pdfDoc.Open();

int inblig=100;
int inbcol=5;
PdfPTable tableau = new PdfPTable(inbcol);
tableau.HeaderRows = 1; // La premiere ligne du tableau est egalement le titre

// Creation du titre
for (int icol = 0; icol < inbcol; icol++)
tableau.AddCell(String.Format("COL {0}", icol));

// Creation d'un tableau de 5 colonnes avec 100 lignes
// pour faire un test sur le titre lors d'un changement de page
for (int ilig = 0; ilig < inblig; ilig++)
for (int icol = 0; icol < inbcol; icol++)
tableau.AddCell(String.Format("CELL {0}.{1}",ilig,icol));

// Ajout du tableau dans le document
pdfDoc.Add(tableau);

// Ajout de paragraphe dans le document
for (int i = 0; i < 200; i++)
pdfDoc.Add(new Paragraph("Paragraphe N° "+i.ToString()));
}
catch (DocumentException de)
{
Console.WriteLine("error " + de.Message);
}
catch (System.IO.IOException ioe)
{
Console.WriteLine("error " + ioe.Message);
}

pdfDoc.Close();
}
}

}

Aucun commentaire: