Saltar al contenido
Codifíca.me | Desarrollo web | Programación

Cómo utilizar PDF con Java mediante ITEXT

25 agosto, 2010

Cómo utilizo PDF con Java

Si queremos crear documentos PDF con Java existen múltiples librerias que nos ayudarán a generarlos, en este articulo vamos a hablar sobre la librería ITEXT.

Qué es ITEXT

ITEXT a parte de ser una buena librería para generar PDF con Java tiene la ventaja de que se integra facilmente con SPRING a la hora de desarrollar aplicaciones Web.

Los datos pueden ser escritos a un fichero o, por ejemplo, desde un servlet a un navegador web.

Cuáles son sus características principales

– Generación de documentos PDF con Java (parrafos, tablas, imágenes, encabezados y pies de pagina…)

– Generar documentos dinámicos a partir de archivos XML o bases de datos

– Agregar marcadores de libros, números de página, marcas de agua, etc

– Split, concatenar, y manipular las páginas PDF con Java.

– Automatizar el llenado de formularios PDF con Java.

– Agregar firma digital a un archivo PDF con Java.

Cómo realizar la INSTALACIÓN:

Para empezar veamos donde descargarnos la librería

Esta es la web de la librería itext, aquí se puede ver la API, ejemplos y tutoriales:

http://itextpdf.com/

Una vez que seleccionamos y descargamos la versión para Java nos redirecciona a esta otra página:

http://sourceforge.net/projects/itext/files/

Actualmente la versión más reciente es la 5.0.2 (2011)

Una vez que nos hemos descargado la librería, la añadimos al CLASSPATH de nuestro proyecto Java para poder utilizarla.

Ejemplo creación PDF con Java:

Este ejemplo abarca la creación de un documento PDF con Java simple, para ver ejemplos mas complejos nos podemos descargar de la propia página muchos ejemplos que abarcan toda la funcionalidad de esta libreria:

http://www.itextpdf.com/examples/index.php itext pdf

Este es el código con itext

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import java.io.FileOutputStream;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.<strong>pdf</strong>.ColumnText;
import com.itextpdf.text.<strong>pdf</strong>.PdfPCell;
import com.itextpdf.text.<strong>pdf</strong>.PdfPTable;
import com.itextpdf.text.<strong>pdf</strong>.PdfPageEventHelper;
import com.itextpdf.text.<strong>pdf</strong>.PdfWriter;
 
public class Test {
 
//Nombre del fichero <strong>PDF</strong> Resultante de la ejecucion
public static final String RESULT = “Ejemplo1.<strong>pdf</strong>;
//Titulos
public static final String CHUNK = “CHUNK”;
public static final String PHRASE = “PHRASE”;
public static final String PARAGRAPH = “PARAGRAPH”;
public static final String TABLE = “TABLE”;
public static final String IMAGE = “IMAGE”;
//Textos
public static final String SEPARADOR = “———————————————————————————————————————-;
public static final String CHUNK1 =This is the smallest significant part of text that can be added to a document.”;
public static final String CHUNK2 = “Most elements can be divided in one or more Chunks. A chunk is a String with a certain Font. All other layout parameters should be defined in the object to which this chunk of text is added.”;
public static final String PHRASE1 = “A Phrase is a series of Chunks.”;
public static final String CHUNKPHRASE21 = “A Phrase has a main Font,”;
public static final String CHUNKPHRASE22 = ” but some chunks within the phrase can have a Font that differs from the main Font.”;
public static final String CHUNKPHRASE23 = ” All the Chunks in a Phrase  have the same leading.”;
public static final String PARAGRAPH1 = “A Paragraph is a series of Chunks and/or Phrases.”;
public static final String PARAGRAPH2 = “A Paragraph has the same qualities of a Phrase, but also some additional layout-parameters: The indentation AND The alignment of the text”;
 
public static void main (String[] args) {
try
{
//Creacion del documento con un tamaño y unos margenes predeterminados
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
//Al documento se le puede añadir cierta metaInformacion
document.addAuthor(“FJHO”);
document.addTitle(“EJEMPLO1″);
 
//A DocWriter class for PDF con Java.
//When this PdfWriter is added to a certain PdfDocument,
//the <strong>PDF</strong> representation of every Element added to this Document will be written to the outputstream.
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
//LEADING = separacion entre lineas del documento
writer.setInitialLeading(16);
Rectangle rct = new Rectangle(36, 54, 559, 788);
//Definimos un nombre y un tamaño para el PageBox los nombres posibles son: “crop”, “trim”, “art” and “bleed”.
writer.setBoxSize(“art”, rct);
 
//Se crea una instancia de la clase que pinta la cabecera y el pie de pagina y se le asignan los eventos que ocurran en el <strong>PDF</strong>
//La en la clase HeaderFooter se capturarar el evento onEndPage para pintarlos
HeaderFooter event = new HeaderFooter();
writer.setPageEvent(event);
 
//Opens the document.
//You have to open the document before you can begin to add content to the body of the document.
document.open();
//Ejemplos de CHUNKS
//Creamos el CHUNK definiendo su tipo de letra, tamaño…
Chunk titulo = new Chunk(CHUNK, FontFactory.getFont(FontFactory.COURIER, 20, Font.UNDERLINE, BaseColor.BLACK));
//Lo añadimos al documento
document.add(titulo);
//CHUNK predefinido, es un salto de linea
document.add(Chunk.NEWLINE);
Chunk chunkSeparador =  new Chunk(SEPARADOR);
Chunk chunkNormal = new Chunk(CHUNK1);
document.add(chunkNormal);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
Chunk chunkTunning = new Chunk(CHUNK2,FontFactory.getFont(FontFactory.COURIER, 20, Font.ITALIC, BaseColor.GREEN));
document.add(chunkTunning);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
Chunk chunkTunning2 = new Chunk(CHUNK2,new Font(FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));
chunkTunning2.setBackground(BaseColor.BLACK, 10f, 10f, 10f, 10f);
document.add(chunkTunning2);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
document.add(chunkSeparador);
//FIN Ejemplos de CHUNKS
//**************************************************************
//Ejemplos de PHRASES
titulo = new Chunk(PHRASE, FontFactory.getFont(FontFactory.COURIER, 20, Font.UNDERLINE, BaseColor.BLACK));
document.add(titulo);
document.add(Chunk.NEWLINE);
Phrase phraseNormal = new Phrase(PHRASE1);
document.add(phraseNormal);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
Phrase phraseTunning = new Phrase(new Chunk(CHUNKPHRASE21));
phraseTunning.add(new Chunk(CHUNKPHRASE22, FontFactory.getFont(FontFactory.COURIER, 5, Font.ITALIC, BaseColor.GREEN)));
phraseTunning.add(new Chunk(CHUNKPHRASE23, FontFactory.getFont(FontFactory.TIMES_ROMAN, 15, Font.BOLD, BaseColor.ORANGE)));
document.add(phraseTunning);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
Phrase phraseConLeading = new Phrase(30, “Todo es la misma frase LEADING de esta PHRASE=100, Todo es la misma frase LEADING de esta PHRASE=100, Todo es la misma frase LEADING de esta PHRASE=100);
document.add(phraseConLeading);
document.add(Chunk.NEWLINE);
document.add(chunkSeparador);
//FIN Ejemplos de PHRASES
//**************************************************************
//Ejemplos de PARAGRAPH
titulo = new Chunk(PARAGRAPH, FontFactory.getFont(FontFactory.COURIER, 20, Font.UNDERLINE, BaseColor.BLACK));
document.add(titulo);
document.add(Chunk.NEWLINE);
// Añadir parrafo sin formato
document.add(new Paragraph(PARAGRAPH1));
Paragraph par = new Paragraph(PARAGRAPH2);
par.setIndentationLeft(200);
document.add(par);
par = new Paragraph(PARAGRAPH2);
par.setIndentationRight(300);
document.add(par);
// Añadir parrafo en Negrita
par = new Paragraph(PARAGRAPH2);
par.getFont().setStyle(Font.BOLD);
par.setAlignment(Element.ALIGN_CENTER);
document.add(par);
// Añadir parrafo en Cursiva
par = new Paragraph(PARAGRAPH2);
par.getFont().setStyle(Font.ITALIC);
par.setAlignment(Element.ALIGN_RIGHT);
document.add(par);
// Añadir parrafo tunning
par = new Paragraph(PARAGRAPH2,
FontFactory.getFont(“arial”,   // fuente
16,                    // tamaño
Font.ITALIC,           // estilo
BaseColor.RED));       // color
document.add(par);
par.setAlignment(Element.ALIGN_LEFT);
document.add(chunkSeparador);
document.add(Chunk.NEWLINE);
document.add(Chunk.NEWLINE);
//FIN Ejemplos de PARAGRAPH
//**************************************************************
//Ejemplos de TABLE
titulo = new Chunk(TABLE, FontFactory.getFont(FontFactory.COURIER, 20, Font.UNDERLINE, BaseColor.BLACK));
document.add(titulo);
//Añadir tabla 5 columnas
PdfPTable table = new PdfPTable(5);
//Añadir CABECERA
PdfPCell cell = new PdfPCell(new Phrase(“CABECERA”));
cell.setColspan(5);
cell.setBackgroundColor(BaseColor.GREEN);
table.addCell(cell);
//Añadir dos filas de celdas sin formato
table.addCell(1.1);
table.addCell(1.2);
table.addCell(1.3);
table.addCell(1.4);
table.addCell(1.5);
table.addCell(2.1);
table.addCell(2.2);
table.addCell(2.3);
table.addCell(2.4);
table.addCell(2.5);
//tunning de Celdas
cell = new PdfPCell(new Phrase(“Alto 3 celdas”));
cell.setRowspan(2);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell);
table.addCell(3.1);
table.addCell(3.2);
table.addCell(3.3);
table.addCell(3.4);
table.addCell(4.1);
table.addCell(4.2);
table.addCell(4.3);
table.addCell(4.4);
table.addCell(5.1);
cell = new PdfPCell(new Phrase(“Ancho 4 celdas”));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setColspan(4);
table.addCell(cell);
document.add(table);
document.add(chunkSeparador);
//FIN Ejemplos de TABLE
//**************************************************************
//Ejemplos de IMAGE
titulo = new Chunk(IMAGE, FontFactory.getFont(FontFactory.COURIER, 20, Font.UNDERLINE, BaseColor.BLACK));
document.add(titulo);
Image foto = Image.getInstance(“resources/ferrari.jpg);
foto.scaleToFit(100, 100);
foto.setAlignment(Chunk.ALIGN_MIDDLE);
document.add(foto);
//FIN Ejemplos de IMAGE
//**************************************************************
// Cierre del documento
document.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
 
static class HeaderFooter extends PdfPageEventHelper {
 
public void onEndPage (PdfWriter writer, Document document) {
Rectangle rect = writer.getBoxSize(“art”);
//CABECERA
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_RIGHT, new Phrase(<strong>LaMandarinaMecanica</strong>),
rect.getRight(), rect.getTop(), 0);
//PIE
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_CENTER, new Phrase(String.format(“page %d”, writer.getPageNumber())),
(rect.getLeft() + rect.getRight()) / 2, rect.getBottom()18, 0);
}
}
}

WEB:

Si lo que necesitamos es generar documentos PDF dinamicamente que se le abran al usuario directamente al interactuar con una página web (pinchar botones, links…), podemos crear un servlet que reciba las peticiones de creacion de ficheros PDF

pdf con java itext programacion

Código pdf dinámico con Java itext:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.<strong>pdf</strong>.PdfWriter;
 
public class Demo extends HttpServlet {
 
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
 
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
 
/*GENERACION AL VUELO DE <strong>PDF</strong>*/
try {
// Texto que va a ser añadido al <strong>PDF</strong>
String text = “Generacion al Vuelo de un <strong>PDF</strong>;
 
// Paso 1: Creamos el documento
Document document = new Document();
// Paso 2: Creamos un ByteArrayOutputStream
// todo lo que se escriba en el documento
// se escribe tambien en el ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
// Abrimos el documento
document.open();
// Escribimos
document.add(new Paragraph(text));
// Cerramos
document.close();
 
// Hay que configurar las cabeceras para que
//el navegador detecte que es un <strong>PDF</strong>
response.setHeader(“Expires”, “0);
response.setHeader(“Cache-Control”,
“must-revalidate, post-check=0, pre-check=0);
response.setHeader(“Pragma”, “public);
// Configuramos el content type
response.setContentType(“application/<strong>pdf</strong>);
// Tamaño
response.setContentLength(baos.size());
// Esccribir el ByteArrayOutputStream a el ServletOutputStream
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
}
catch(com.itextpdf.text.DocumentException e) {
throw new IOException(e.getMessage());
}
}
}

PDF con Java itext

Entradas relacionadas

Deja una respuesta

Tu dirección de correo electrónico no será publicada.

Comentarios (12)

Excelente tutorial.

Responder

Hola amigos. estoy aprendiendo ITEXT version 5. quiero tener un header y footer en el header una imagen que se repita. en cada pagina este es mi codigo.
public class HeaderAndFooter extends PdfPageEventHelper
{
private final Phrase Phrase;
private final Font FooterFont = new Font(Font.FontFamily.HELVETICA,10,Font.BOLD);
private final Integer Year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);
private final String CopyRight;
public HeaderAndFooter()
{
StringBuilder Builder = new StringBuilder(“Corporacion Droling”);
FooterFont.setColor(BaseColor.BLUE);
Builder.append(Year).append(‘.’).append(” “).append(“#Pagina: %d”);
CopyRight = Builder.toString();
Phrase = new Phrase(getChunk()); //The Image is Loaded here with success.. :thumbup:
return;
}
@Override
public void onEndPage (PdfWriter writer, Document document)
{
Rectangle rect = writer.getBoxSize(“art”);
//[Header]new Phrase(Chunk) Chunk have the image…. Not working Nothing Show..
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_LEFT,Phrase,rect.getRight(), rect.getTop(),0);
//Footer runs Smootly..
ColumnText.showTextAligned(writer.getDirectContent(),Element.ALIGN_CENTER, new Phrase(String.format(CopyRight,writer.getPageNumber()),FooterFont),(rect.getLeft() + rect.getRight()) / 2, rect.getBottom() – 18, 0);
}
private Chunk getChunk()
{
Chunk Chunk = null;
try
{
final java.net.URL URL = CellsHeights.class.getResource(“/org/com/Utilities/PDF/Images/JavaLogo.jpg”);
Image Imagex = Image.getInstance(URL);
Imagex.setAlignment(Image.MIDDLE);
Imagex.setAlt(“Corporacion Droling”);
Imagex.scalePercent(100);
Chunk = new Chunk(Imagex,0,0);
}catch(Exception e){System.err.println(e.getMessage());}
finally{return Chunk;}
}
}
. el footer sale bien pero la imagen en el header no sale nada alguien sabe como colocar la imagen en el header con itext5.

Responder

Hola yo lo que necesito es un encabezado complejo: una imagen y texto que paso como parámetros, además necesito un pie de pagina que me soporte una imagen y una tabla, con itext se vuelve tan complejo de hacer no existe por allí alguna librería como fpdf en php que lo hace de manera super sencilla por allí encontré fpdf para java pero aun no esta tan maduro

Responder

Hola Percy, desconozco como funciona fpdf, tendría que mirarlo y ahora no estoy con esto.
Siento no poderte ayudar.
Un saludo.

Responder

Buenas querría saber si es posible escribir sobre un .pdf ya creado. Tengo un pdf con una imagen de fondo y quiero escribir sobre esta.
Gracias

Responder

Antes que nada excelente ejemplo de aplicación de la librería itextpdf, actualmente estoy desarrollando un sistema de facturas el cual me entrega todo el reporte en pdf, solo que tengo un problema que no he podido solucionar, esta libreria tiene alguna forma de poder poner texto en una coordenada especifica dentro de la hoja del pdf.

Sin mas agradezco su ayuda.

Saludos.

Responder

Muy buen tutorial muy completo, bueno yo ya he creado reportes pdf con itext pero hasta ahora los hago de manera general y quisiera saber si no tienen un ejemplo de como crear reportes pdf con itext para jsp, de manera individual que al momento de poner fecha solo me arroje por fecha por nombre. Les agradeceria mucho su ayuda muchas gracias DLB MUCHO

Responder

Buenas Vane,
Hace ya mucho tiempo que no tocamos nada de itext, y no tengo ningún ejemplo parecido a lo que nos comentas. Siento no poder ayudarte en este momento.
Un saludo.

Responder

Cordial Saludo y Agradecimiento de Antemano.
Después de crear un archivo PDF con dos páginas, ¿Cómo hago para escribir texto en ambas páginas?, es decir, luego de escribir texto en la segunda página, necesito volver a escribir texto en la primer página; y esto sucede dentro de un bucle, lo que indica que se escribe texto en ambas páginas varias veces.
Supongo Yo, que es como mantener las dos páginas habilitadas para la escritura.

Responder

hola .. yo estoy usando esta librería, y quisiera saber si alguno de ustedes. sabe como poner tipo de letras en las tablas, o usar tipo d letras negritas?? alguna linea que me permita modificar el interlineado del texto en general ??? xfis ayuda aun no se como hacer esto… gracias 🙂

Responder

[…] múltiples librerias que nos ayudarán a generarlos, en este articulo vamos a hablar … Download Cómo utilizar PDF con Java mediante ITEXT | Código Java … | […]

Responder

hola quiero extraer solo una parte de un contenido de un hoja por ejemplo la parte del resumen d eun libro q esta en pdf

Responder