Codi Xules

Avui veurem iText una llibreria PDF en Java que ens permet crear, analitzar, modificar i mantenir documents en el format PDF. iText no és usat només per Java també s’utilitza en .NET, Android and GAE per aportar a les seves aplicacions funcionalitats amb PDF.

iText logo

què ens proporciona iText?

iText és una llibreria PDF que ens permet crear, adaptar, revisar i mantenir documents en el format de document PDF, algunes de les principals característiques són:

  • Generar documents i els informes extrets d’un fitxer XML o d’una base de dades
  • Crear mapes i llibres, incorporant característiques interactives en format PDF
  • Afegir marcadors , números de pàgina, marques d’aigua, i altres característiques als documents PDF existents a Split o concatenar les pàgines dels arxius PDF existents
  • Omplir formularis interactius.
  • Servir generat dinàmicament o manipular documents PDF en un navegador web.

Java iText PDF – en creant un pdf en Java amb iText

  1. Afegim les llibreries i cre amos la classe
  2. Creació d’el document i metadades
  3. Creem la nostra primera pàgina
  4. Afegim més elements de iText al nostre PDF
  5. Ús de taules en iText: PDFPTable
  6. Resultat Final (Codi complet)
  7. Documentació utilitzada

Programari i eines utilitzades

  • Netbeans
  • Java
  • iText PDF

a

Hi afegim les llibreries i vam crear la classe

Començarem descarregant la l’última versió d’aquesta llibreria, pots accedir a Sourceforge o descarregar-la des d’aquest enllaç: Descàrrega de iText des Sourceforge.

Configurem el projecte

Per aquest projecte utilitzarem Netbeans que proporciona un gran suport per al desenvolupament d’aplicacions amb Java.

per a això vam obrir Netbeans i busquem l’opció New Project, a l’obrir-se el wizard seleccionem Java > Java Application, després únicament li donarem nom al nostre projecte i el seu ubic ació.

Podeu fer servir qualsevol altre IDE per a Java l’únic que necessitaràs realment és afegir les llibreries de iText.

Creem la classe

Per a crear una nova classe ens situem sobre el projecte i en el menú pop-up seleccionem New > Java Class, aquí introduirem el nom de la classe i el paquet on la volem situar, en el meu cas:

  • Nom de la classe: GeneratePDFFileIText.java
  • Paquet: org.xulescode.itext

Aquest codi pretén ser la més senzill possible, així que col·locarem tot el codi dins de l’mètode: public void CreatePDF (File pdfNewFile) per poder seguir a manera de guió com vam crear un document PDF, afegeixo ja unes variables de fonts i una ubicació per a una imatge que utilitzaré en l’exemple:

package org.xulescode.itext;import com.itextpdf.*;import java.io.*; /** * Example of using the iText library to work with PDF documents on Java, * lets you create, analyze, modify and maintain documents in this format. * Ejemplo de uso de la librería iText para trabajar con documentos PDF en Java, * nos permite crear, analizar, modificar y mantener documentos en este formato. * * @author xules You can follow me on my website http://www.codigoxules.org/en * Puedes seguirme en mi web http://www.codigoxules.org */public class GeneratePDFFileIText { private static final Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 26, Font.BOLDITALIC); private static final Font paragraphFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL); private static final Font categoryFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD); private static final Font subcategoryFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD); private static final Font blueFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED); private static final Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD); private static final String iTextExampleImage = "/home/xules/codigoxules/iText-Example-image.png"; /** * We create a PDF document with iText using different elements to learn * to use this library. * Creamos un documento PDF con iText usando diferentes elementos para aprender * a usar esta librería. * @param pdfNewFile <code>String</code> * pdf File we are going to write. * Fichero pdf en el que vamos a escribir. */ public void createPDF(File pdfNewFile) { // Aquí introduciremos el código para crear el PDF. }}

a

Creació d’el document i metadades

En aquest primer pas amb Java iText PDF necessitem crear un document per a treballar amb ell i anar afegint les diferents pàgines que necessitem per al nostre exemple: Document document = new Document () ;, un cop creat anem a associar el document de treball amb el fitxer de sortida això ho fem amb el mètode com.itextpdf.text.pdf.PdfWriter, aquest és el codi que necessitem:

 // We create the document and set the file name. // Creamos el documento e indicamos el nombre del fichero. try { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile)); } catch (FileNotFoundException fileNotFoundException) { System.out.println("No such file was found to generate the PDF " + "(No se encontró el fichero para generar el pdf)" + fileNotFoundException); } document.open(); // AQUÍ COMPLETAREMOS NUESTRO CÓDIGO PARA GENERAR EL PDF document.close(); System.out.println("Your PDF file has been generated!(¡Se ha generado tu hoja PDF!"); } catch (DocumentException documentException) { System.out.println("The file not exists (Se ha producido un error al generar un documento): " + documentException); }

Ara anem afegir informació al nostre document creat amb Java iText PDF introduint les metadades, aquests s’afegeixen directament en els valors de el document definit anteriorment: document:

 // We add metadata to PDF // Añadimos los metadatos del PDF document.addTitle("Table export to PDF (Exportamos la tabla a PDF)"); document.addSubject("Using iText (usando iText)"); document.addKeywords("Java, PDF, iText"); document.addAuthor("Código Xules"); document.addCreator("Código Xules");

a

Creem la nostra primera pàgina

Per a la creació d’aquesta primera pàgina farem servir els elements generals:

  • com.itextpdf.text.Chunk: el la part més petita que es pot afegir a un document, la major part dels elements es poden dividir en diversos Chunks i bàsicament és un String amb una font determinada.
  • com.itextpdf.text.Image: representació gràfica d’imatges podem utilitzar: JPEG, PNG o GIF.
  • com.itextpdf.text.Paragraph: és una sèrie de chunks.

I l’element com.itextpdf.text.Chapter que fem servir per afegir unes secció especial i que és de on anem a penjar en aquest exemple els elements anteriorment esmentats, el pots consultar en el codi:

 // First page // Primera página Chunk chunk = new Chunk("This is the title", chapterFont); chunk.setBackground(BaseColor.GRAY); // Let's create de first Chapter (Creemos el primer capítulo) Chapter chapter = new Chapter(new Paragraph(chunk), 1); chapter.setNumberDepth(0); chapter.add(new Paragraph("This is the paragraph", paragraphFont)); // We add an image (Añadimos una imagen) Image image; try { image = Image.getInstance(iTextExampleImage); image.setAbsolutePosition(2, 150); chapter.add(image); } catch (BadElementException ex) { System.out.println("Image BadElementException" + ex); } catch (IOException ex) { System.out.println("Image IOException " + ex); } document.add(chapter);

a

Afegim més elements d’iText al nostre PDF

Ara simplement afegim uns elements a la nostra nova pàgina per seguir provant elements, en primer lloc vam crear un nou capítol a què li donem nom utilitzant com.itextpdf.text.Paragraph, també vam crear un altre que afegirem a continuació:

 // Second page - some elements // Segunda página - Algunos elementos Chapter chapSecond = new Chapter(new Paragraph(new Anchor("Some elements (Añadimos varios elementos)")), 1); Paragraph paragraphS = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont);

Per a mostrar que es poden fer moltes coses afegim un exemple de coma subratllar un paràgraf amb una línia de punts , exemple tret de l’bloc de Java iText PDF, i en el qual es fa servir l’element com.itextpdf.text.pdf.draw.DottedLineSeparator que dibuixa una línia de punts d’esquerra a dreta:

 // Underline a paragraph by iText (subrayando un párrafo por iText) Paragraph paragraphE = new Paragraph("This line will be underlined with a dotted line (Está línea será subrayada con una línea de puntos)."); DottedLineSeparator dottedline = new DottedLineSeparator(); dottedline.setOffset(-2); dottedline.setGap(2f); paragraphE.add(dottedline); chapSecond.addSection(paragraphE);

per fer un exemple senzill de llistes afegim de l’exemple: List examples de iText, simplement per mostrar un exemple d’ús i veure el senzill que és de gestionar com.itextpdf.text.List:

 Section paragraphMoreS = chapSecond.addSection(paragraphS); // List by iText (listas por iText) String text = "test 1 2 3 "; for (int i = 0; i < 5; i++) { text = text + text; } List list = new List(List.UNORDERED); ListItem item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); text = "a b c align "; for (int i = 0; i < 5; i++) { text = text + text; } item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); text = "supercalifragilisticexpialidocious "; for (int i = 0; i < 3; i++) { text = text + text; } item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); paragraphMoreS.add(list); document.add(chapSecond);

a l’acabar, no podem oblidar-nos afegir el nostre codi a el document amb document.add (…).

a

Ús de taules en iText: PDFPTable

En aquest apartat ens centrem en l’ús de com.itextpdf.text.pdf.PdfPTable creant una nova pàgina, que es convertiran en diverses com veurem, per la longitud de la taula que implementarem per veure el funcionament de com.itextpdf.text.pdf.PdfPTable.

en primer lloc en el codi afegim diversos elements per afegir títol i subtítol, que no explicaré més doncs utilitzem elements anteriorment explicats i per a més detalls ja ho pots veure directament en el codi.

Centrem-nos en com.itextpdf.text.pdf.PdfPTable que és un element que ens permet crear una taula la posició pot ser absoluta però que també es pot afegir directament a el document. En aquest exemple simplement afegim text, però serà molt útil per a omplir per exemple amb les dades obtingudes de la base de dades.

Els passos que seguim amb els següents i els pots consultar en el codi:

  • Creem la taula: PdfPTable table = new PdfPTable (numColumns);
  • Afegim les capçaleres de la taula: columnHeader = new PdfPCell (new Phrase ( “COL” + column));
  • Omplim el contingut de la taula amb un bucle for afegint cada cel·la amb el codi: table.addCell ( “Row” + row + “- Col” + column);
  • Finalment, afegirem la taula a el document, afegint-la en aquest cas (no té perquè ser així) a el paràgraf que vam crear a el principi perquè vagi a continuació.

Aquest és el codi:

 // How to use PdfPTable // Utilización de PdfPTable // We use various elements to add title and subtitle // Usamos varios elementos para añadir título y subtítulo Anchor anchor = new Anchor("Table export to PDF (Exportamos la tabla a PDF)", categoryFont); anchor.setName("Table export to PDF (Exportamos la tabla a PDF)"); Chapter chapTitle = new Chapter(new Paragraph(anchor), 1); Paragraph paragraph = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont); Section paragraphMore = chapTitle.addSection(paragraph); paragraphMore.add(new Paragraph("This is a simple example (Este es un ejemplo sencillo)")); Integer numColumns = 6; Integer numRows = 120; // We create the table (Creamos la tabla). PdfPTable table = new PdfPTable(numColumns); // Now we fill the PDF table // Ahora llenamos la tabla del PDF PdfPCell columnHeader; // Fill table rows (rellenamos las filas de la tabla). for (int column = 0; column < numColumns; column++) { columnHeader = new PdfPCell(new Phrase("COL " + column)); columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(columnHeader); } table.setHeaderRows(1); // Fill table rows (rellenamos las filas de la tabla). for (int row = 0; row < numRows; row++) { for (int column = 0; column < numColumns; column++) { table.addCell("Row " + row + " - Col" + column); } } // We add the table (Añadimos la tabla) paragraphMore.add(table); // We add the paragraph with the table (Añadimos el elemento con la tabla). document.add(chapTitle); document.close(); System.out.println("Your PDF file has been generated!(¡Se ha generado tu hoja PDF!");

a

Resultat Final (codi complet)

Ja hem completat el nostre codi per generar un PDF amb iText, ara només hem de executar des del nostre mètode main:

 /** * @param args the command line arguments */ public static void main(String args) { GeneratePDFFileIText generatePDFFileIText = new GeneratePDFFileIText(); generatePDFFileIText.createPDF(new File("/home/xules/codigoxules/GeneratePDFFileIText.pdf")); }

A l’enllaç pots descarregar el codi complet d’aquest exemple:

Icona

Generació d’un PDF des de Java amb iText

1 arxiu (s) 8.75 KB

a

També, pots veure el codi complet directament:

package org.xulescode.itext;import com.itextpdf.text.Anchor;import com.itextpdf.text.BadElementException;import com.itextpdf.text.BaseColor;import com.itextpdf.text.Chapter;import com.itextpdf.text.Chunk;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Element;import com.itextpdf.text.Font;import com.itextpdf.text.FontFactory;import com.itextpdf.text.Image;import com.itextpdf.text.List;import com.itextpdf.text.ListItem;import com.itextpdf.text.Paragraph;import com.itextpdf.text.Phrase;import com.itextpdf.text.Section;import com.itextpdf.text.pdf.PdfPCell;import com.itextpdf.text.pdf.PdfPTable;import com.itextpdf.text.pdf.PdfWriter;import com.itextpdf.text.pdf.draw.DottedLineSeparator;import java.io.*; /** * Example of using the iText library to work with PDF documents on Java, * lets you create, analyze, modify and maintain documents in this format. * Ejemplo de uso de la librería iText para trabajar con documentos PDF en Java, * nos permite crear, analizar, modificar y mantener documentos en este formato. * * @author xules You can follow me on my website http://www.codigoxules.org/en * Puedes seguirme en mi web http://www.codigoxules.org */public class GeneratePDFFileIText { // Fonts definitions (Definición de fuentes). private static final Font chapterFont = FontFactory.getFont(FontFactory.HELVETICA, 26, Font.BOLDITALIC); private static final Font paragraphFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL); private static final Font categoryFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD); private static final Font subcategoryFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD); private static final Font blueFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED); private static final Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD); private static final String iTextExampleImage = "/home/xules/codigoxules/iText-Example-image.png"; /** * We create a PDF document with iText using different elements to learn * to use this library. * Creamos un documento PDF con iText usando diferentes elementos para aprender * a usar esta librería. * @param pdfNewFile <code>String</code> * pdf File we are going to write. * Fichero pdf en el que vamos a escribir. */ public void createPDF(File pdfNewFile) { // We create the document and set the file name. // Creamos el documento e indicamos el nombre del fichero. try { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(pdfNewFile)); } catch (FileNotFoundException fileNotFoundException) { System.out.println("No such file was found to generate the PDF " + "(No se encontró el fichero para generar el pdf)" + fileNotFoundException); } document.open(); // We add metadata to PDF // Añadimos los metadatos del PDF document.addTitle("Table export to PDF (Exportamos la tabla a PDF)"); document.addSubject("Using iText (usando iText)"); document.addKeywords("Java, PDF, iText"); document.addAuthor("Código Xules"); document.addCreator("Código Xules"); // First page // Primera página Chunk chunk = new Chunk("This is the title", chapterFont); chunk.setBackground(BaseColor.GRAY); // Let's create de first Chapter (Creemos el primer capítulo) Chapter chapter = new Chapter(new Paragraph(chunk), 1); chapter.setNumberDepth(0); chapter.add(new Paragraph("This is the paragraph", paragraphFont)); // We add an image (Añadimos una imagen) Image image; try { image = Image.getInstance(iTextExampleImage); image.setAbsolutePosition(2, 150); chapter.add(image); } catch (BadElementException ex) { System.out.println("Image BadElementException" + ex); } catch (IOException ex) { System.out.println("Image IOException " + ex); } document.add(chapter); // Second page - some elements // Segunda página - Algunos elementos Chapter chapSecond = new Chapter(new Paragraph(new Anchor("Some elements (Añadimos varios elementos)")), 1); Paragraph paragraphS = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont); // Underline a paragraph by iText (subrayando un párrafo por iText) Paragraph paragraphE = new Paragraph("This line will be underlined with a dotted line (Está línea será subrayada con una línea de puntos)."); DottedLineSeparator dottedline = new DottedLineSeparator(); dottedline.setOffset(-2); dottedline.setGap(2f); paragraphE.add(dottedline); chapSecond.addSection(paragraphE); Section paragraphMoreS = chapSecond.addSection(paragraphS); // List by iText (listas por iText) String text = "test 1 2 3 "; for (int i = 0; i < 5; i++) { text = text + text; } List list = new List(List.UNORDERED); ListItem item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); text = "a b c align "; for (int i = 0; i < 5; i++) { text = text + text; } item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); text = "supercalifragilisticexpialidocious "; for (int i = 0; i < 3; i++) { text = text + text; } item = new ListItem(text); item.setAlignment(Element.ALIGN_JUSTIFIED); list.add(item); paragraphMoreS.add(list); document.add(chapSecond); // How to use PdfPTable // Utilización de PdfPTable // We use various elements to add title and subtitle // Usamos varios elementos para añadir título y subtítulo Anchor anchor = new Anchor("Table export to PDF (Exportamos la tabla a PDF)", categoryFont); anchor.setName("Table export to PDF (Exportamos la tabla a PDF)"); Chapter chapTitle = new Chapter(new Paragraph(anchor), 1); Paragraph paragraph = new Paragraph("Do it by Xules (Realizado por Xules)", subcategoryFont); Section paragraphMore = chapTitle.addSection(paragraph); paragraphMore.add(new Paragraph("This is a simple example (Este es un ejemplo sencillo)")); Integer numColumns = 6; Integer numRows = 120; // We create the table (Creamos la tabla). PdfPTable table = new PdfPTable(numColumns); // Now we fill the PDF table // Ahora llenamos la tabla del PDF PdfPCell columnHeader; // Fill table rows (rellenamos las filas de la tabla). for (int column = 0; column < numColumns; column++) { columnHeader = new PdfPCell(new Phrase("COL " + column)); columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(columnHeader); } table.setHeaderRows(1); // Fill table rows (rellenamos las filas de la tabla). for (int row = 0; row < numRows; row++) { for (int column = 0; column < numColumns; column++) { table.addCell("Row " + row + " - Col" + column); } } // We add the table (Añadimos la tabla) paragraphMore.add(table); // We add the paragraph with the table (Añadimos el elemento con la tabla). document.add(chapTitle); document.close(); System.out.println("Your PDF file has been generated!(¡Se ha generado tu hoja PDF!"); } catch (DocumentException documentException) { System.out.println("The file not exists (Se ha producido un error al generar un documento): " + documentException); } } /** * @param args the command line arguments */ public static void main(String args) { GeneratePDFFileIText generatePDFFileIText = new GeneratePDFFileIText(); generatePDFFileIText.createPDF(new File("/home/xules/codigoxules/GeneratePDFFileIText.pdf")); }}

aquest és el PDF que s’obté com a resultat final d’aquest exemple:

Icona

Generate PDF File iText des de Java

1 arxiu (s) 157.59 KB

Deixa un comentari

L'adreça electrònica no es publicarà. Els camps necessaris estan marcats amb *