0% encontró este documento útil (0 votos)
21 vistas5 páginas

Generar PDF en Java con iText

Este documento explica cómo generar un PDF con el número de página actual y total usando Java. Describe descargar la biblioteca iText y crear un proyecto en NetBeans. Luego, muestra el código para generar un PDF de 3 páginas con el número de página en el pie de página, por ejemplo "Página 1 de 3". Al ejecutar el proyecto, se crea el PDF en la carpeta del proyecto.
Derechos de autor
© Attribution Non-Commercial (BY-NC)
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
21 vistas5 páginas

Generar PDF en Java con iText

Este documento explica cómo generar un PDF con el número de página actual y total usando Java. Describe descargar la biblioteca iText y crear un proyecto en NetBeans. Luego, muestra el código para generar un PDF de 3 páginas con el número de página en el pie de página, por ejemplo "Página 1 de 3". Al ejecutar el proyecto, se crea el PDF en la carpeta del proyecto.
Derechos de autor
© Attribution Non-Commercial (BY-NC)
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd

Sguenosen: CONOCIMIENTO LIBRE CON SOFTWARE LIBRE

EL EQUIPO TUTORIALES BLOGROLL ENLACES LICENCIA CONTACTO

Search

Archivos

Como generar un archivo pdf desde Java - Parte V


Publicado el 25 octubre, 2012. 646 Vistas. Sin comentarios

Elegir mes

FLISOL 2013
Me gusta 1

Compartir: Indice de todas las partes:


n n n n n

Parte I - Generarpdfconimgenytexto. Parte II - Generarpdfconheaderdeimgenytexto. Parte III- Generar pdf insertanto una tabla Parte IV - Generarpdfconnmerodepginaenfooter Parte V - GenerarpdfconnmerodepginaXdeYenfooter

Enestaquintayltimapartedelasaga=p,vamosaaprenderagenerarunpdfagregandoel nmerodepginaXdeYalfooterdelarchivo,porejemplo"Pgina5de10".Loprimeroes descargarlalibreraexternaquenosvaaayudardurantetodoelprocedimiento,estasellamaiText. Para este tutorial es la versin5.3.3. iText es una biblioteca Open Source para crear y manipular archivos PDF, RTF, y HTML en Java. Fue escritaporBrunoLowagie,PauloSoares,yotrosestdistribuidabajolaAffero General Public License. DespusdedescargariTextdescomprimensucontenidoenellugarquemslesseaconveniente. Abrimos Netbeans y creamos un nuevo proyecto Java>>Java Application.

Categoras

Android Bases de datos

Charlas/Expos Debian
Documentales

Desktop apps Distribuciones


El Salvador Encuestas
Eventos Fedora Garabatos Linux

GNU/Linux Google
MySQL Navegadores

Humor Java Juegos Linux Mint


MacOS Manuales/Guas

Personalizacin PHP Programacin Servidores

Noticias

SolusOS SQLite Tips Ubuntu Varios Videos Web apps Windows


Etiquetas
Anonymous Apache Audio Blender

Chromium

Al nombre del archivo le voy a poner CrearPdfPagXDeY, seleccionas la ruta y desmarcamos crear la clase principal. Creamos un paquete contenedor de nombre "pkgPrincipal" haciendo clic derecho sobre paquete predeterminado>>Nuevo>>Java Package.

Cinnamon Compiz Correo Drupal


Emerald Encuestas

Firefox Gambas Gnome 3 Grub Iceweasel Imgenes Internet LAMPP Mantenimiento Mensajeria Microsoft Netbeans PDF Pelculas
Flash Gimp Gmail MATE Mquinavirtual

Facebook

Redes Redes

Sociales

Repositorios Richard Stallman Seguridad Servicio Social Smartphones Temas Terminal Videotutorial Virtualbox Virus XAMPP
Creamos la clase sobre la que vamos a trabajar de nombre "PdfPagXDeY" haciendo clic derecho sobre pkgPrincipal>>Nuevo>>Java Class.

Xfce
ltimoscomentarios
hug0 { Saludos @tannhausser por

algunaraznquedesconozcoenlas dos... } Vokoscreen no graba audio [solucin]

Generated with [Link]

Page 1 / 5

tannhausser

{ Hola Hug0! Una

Agregamos la biblioteca [Link] derecho sobre "Bibliotecas" y luego "Agregar jar/Carpeta", vas hasta la ruta donde descomprimiste el archivoylanicaquenecesitamosahoritaes"[Link]",laseleccionasyluegoclicenelbotn "Abrir" y ya esta agregada a nuestro proyecto. [Link],nocreoquesea convenienteseccionarelcdigoparaexplicarlo.

herramientamuytilelvokoscreen,al leer... } Vokoscreen no graba audio [solucin] hug0 { Buen aporte, es una suerte que

hayas "encontrado" ese enlace... } Como instalar Netbeans 7.3 en... Grover { Aqui pude encontrar la forma

package pkgPrincipal; import import import import import [Link].*; [Link].*; [Link]; [Link]; [Link];
l

de instalar JDK 7 y... } Como instalar Netbeans 7.3 en... hug0 { Si ese error da siempre al

actualizar,talvezdebincluir...} Como instalar Cinnamon 1.6.7 en...

Recientes
Vokoscreennograbaaudio[solucin] InstalareltemadeconosFaenzaenGNU/Linux Como instalar el paquete de temas Cinnamon en Debian
l l l

//@author hug0 public class PdfPagXDeY { //Ruta del archivo, esto es dentro del proyecto Netbeans public static String archivo=[Link]("[Link]")+"/[Link]"; //Clase para manejar los Header y los Footer //Toma los metodos de PdfPageEventHelper class HeaderFooter extends PdfPageEventHelper { //Templateparaelnmerototaldepginas PdfTemplate total; //Evento cuando que se ejecuta al comenzar una documento @Override public void onOpenDocument(PdfWriter writer, Document document){ //Definimos las medidas del template total = [Link]().createTemplate(10, 16); }

Crear un XML en java a partir de un esquema *.xsd Crear XML en java usando XStream

Top del mes


l

Crea tus cronogramas de actividades online


vista(s)

1,011

ValidacindeJTextField:TextFieldnumrico, binario o solo letras


973 vista(s)

Java: Crear, leer y escribir en un archivo de texto


784 vista(s)

Como instalar Debian Testing/Wheezy paso a paso


617 vista(s) 547 vista(s)

Usando SQLite con Java en NetBeans

//Eventocuandoqueseejecutaalterminarunapgina @Override public void onEndPage(PdfWriter writer, Document document) { //Creamos una tabla de dos culumnas PdfPTable table = new PdfPTable(2); try { //Establecemos las medidas de la tabla [Link](new int[]{24, 10}); [Link](100); //Establecemos la altura de la celda [Link]().setFixedHeight(20); //Quitamos el borde [Link]().setBorder(Rectangle.NO_BORDER); //Alineamos el contenido a la derecha [Link]().setHorizontalAlignment(Element.ALIGN_RIGHT); //Escribimos el primer texto //en la primera celda [Link]([Link]("Pgina%dde",[Link]())) //Obtenemos el template total //y lo agregamos a la celda PdfPCell cell = new PdfPCell([Link](total)); //quitamos el borde [Link](Rectangle.NO_BORDER); //lo agregamos a la tabla [Link](cell); [Link](0, -1, 260, 40, [Link]()); }catch(DocumentException de) { throw new ExceptionConverter(de); } } @Override public void onCloseDocument(PdfWriter writer, Document document) {

Generated with [Link]

Page 2 / 5

//Escribimos el contenido al cerrar el documento [Link](total, Element.ALIGN_LEFT,new Phrase([Link]([Link]() } }

public void createPdf(){ try{ /*Declaramos documento como un objeto Document *Asignamoseltamaodehojaylosmargenes */ Document document = new Document([Link], 80, 80, 75, 75); //writeresdeclaradocomoelmtodoutilizadoparaescribirenelarchivo //Obtenemos la instancia del archivo a utilizar PdfWriter writer = [Link](document, new FileOutputStream(new File(archivo))); //Declaramos una instancia de los eventos en HeaderFooter HeaderFooter event = new HeaderFooter(); [Link](event); //Escribimos un titulo del pdf [Link]("Titulo del PDF"); //Escribimos un autor [Link]("hug0"); //Abrimos el documento [Link](); //Declaramos un texto como Paragraph //Lepodemosdarformadocomoalineacin,tamaoycoloralafuente. Paragraph paragraph= new Paragraph(); [Link](Element.ALIGN_CENTER); [Link](new Font([Link]("Sans",20,[Link], [Link]))); [Link]("Garabatos Linux"); //Agregamos el parrafo al documento [Link](paragraph); //Agregamos una pagina [Link](); //Aadimostexto [Link](newParagraph("Segundapgina")) //Aadimosunanuevapagina [Link](); //Agregamos texto [Link](newParagraph("Tercerapgina")) //Cerramos el documento y la escritura [Link](); [Link](); }catch(FileNotFoundException | DocumentException e){ [Link](); } } public static void main(String[] args) { //Creamos un nuevo pdf new PdfPagXDeY().createPdf(); } } AlejecutarelproyectorevisarlacarpetadelproyectodeNetbeansyahvaaestarnuestropdf.

Generated with [Link]

Page 3 / 5

Ver resultado

iText | Documentacinoficial DescargarCdigo - Ver tutoriales Java

Tags: Java, Manuales/Guas, Programacin.

Autor: hug0
Usuario GNU/Linux desde 2009 y blogger desde 2010. Ingeniero en Sistemas, programador php, algo de Java y Visual Basic, autodidacta por curiosidad y a veces por necesidad. Geek apasionado, no me [Link]!

Post Relacionados

Como generar un archivo pdf desde Java Parte III

Como generar un archivo pdf desde Java Parte IV

Como generar un archivo pdf desde Java Parte II

Como generar un archivo pdf desde Java Parte I

Hola mundo en Java con Netbeans

Dejar un comentario

Name:

Email:

Website (optional):

Message:
5

Submit Recibir un email con los siguientes comentarios a esta entrada. Recibir un email con cada nuevo post.

Garabatos Linux
Like
Computers blogs

Computers &

290 people like Garabatos Linux.

Internet Directory

Generated with [Link]

Page 4 / 5

Facebook social plugin

Copyleft 2010-2013 Garabatos Linux. Theme por [Link] y modificado por hug0.

Generated with [Link]

Page 5 / 5

Common questions

Con tecnología de IA

The PdfWriter class acts as an intermediary that writes the generated content to the PDF file, while the Document class represents the PDF document itself. In the code, PdfWriter.getInstance() links the document to a specific file path. By opening the document using the document.open() method, the PdfWriter can write content such as titles, text, and format elements into the document. As the document is being created, the PdfWriter facilitates adding new pages and managing page events such as headers and footers .

The document demonstrates exception handling in PDF processing by using try-catch blocks around operations prone to fail, such as writing to files. Specific exceptions like FileNotFoundException and DocumentException are caught, allowing for graceful error handling and diagnostics. This method ensures that runtime errors are managed predictably, preventing crashes and providing informative feedback for debugging purposes .

Developers might face challenges such as understanding the comprehensive API, managing PDF layout complexities, and ensuring compatibility with various Java environments. These can be addressed by thoroughly consulting iText's documentation, actively participating in community forums for shared solutions, and testing code across different environments to handle potential compatibility issues. Additionally, using sample codes and tutorials available within the iText community can help familiarize developers with best practices .

The Java code manages headers and footers by utilizing the PdfPageEventHelper class, specifically through the HeaderFooter inner class. This class overrides methods such as onOpenDocument, onEndPage, and onCloseDocument to customize page events. During the onEndPage event, a PdfPTable with two columns is created to add 'Page X of Y' format in the footer. The total number of pages is calculated using a PdfTemplate object, which updates the footer with the correct page count upon closing the document .

Setting up a new project and package in Netbeans is necessary to organize the code logically and manage dependencies effectively. This structure ensures that all libraries, such as iText, are correctly imported and used within the specific context of the project. The package organization facilitates a clear namespace, allowing the code and resources like PDF files to be managed systematically, which is crucial for scalability and maintenance .

The integration of iText with Java enables the creation of dynamic content by allowing developers to programmatically generate and manipulate content based on real-time data. In the provided approach, methods like onEndPage and onCloseDocument dynamically adjust page numbers, while Paragraph objects dynamically compile and format text content. This flexibility is essential for applications requiring real-time document generation, such as invoices or reports, from live datasets .

Organizing the Java PDF generation tutorial into distinct parts improves readability by segmenting complex procedures into manageable steps. Each part focuses on specific tasks—such as adding images or tables—providing clarity and focus. This method aids learners by preventing information overload, allowing them to understand each function comprehensively and apply knowledge incrementally. Clear segmentation also improves troubleshooting and refinement by isolating code sections for easy updates .

The iText library is significant in generating PDFs in Java because it provides robust functionality to create and manipulate PDF documents. This capability is vital for tasks such as adding images, text, headers, footers, and page numbers. Its open-source nature, distributed under the Affero General Public License, allows developers to use, modify, and integrate it into their projects freely, promoting community collaboration and transparency .

Using open-source libraries such as iText in professional environments offers both opportunities and challenges. The primary advantage is cost-effectiveness and robust community support, allowing developers to leverage established tools without incurring licensing fees. However, the Affero GPL requires that modified versions also remain open-source, which may affect proprietary projects. Furthermore, reliance on community-driven updates could present risks if the library's development stagnates. It's crucial for organizations to evaluate these trade-offs concerning project goals and compliance requirements .

The code demonstrates customization by first defining layout parameters in the Document constructor, setting margins with specified values denoting left, right, top, and bottom padding. Paragraph alignment is managed using setAlignment(), allowing content to be centrally positioned. Font customization further refines layout appearance via setFont(), where font style, size, and color can be programmatically controlled, ensuring the document layout aligns with user requirements and aesthetic standards .

También podría gustarte