USANDO IRONPDF PARA JAVA Cómo Crear una Tabla en un Documento PDF Usando Java (Tutorial) Darrius Serrant Actualizado:julio 28, 2025 Download IronPDF Descarga de Maven Descarga de JAR Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article This article will demonstrate how to create tables inside a PDF document using Java. It is necessary to have a third-party library for creating tables in PDF documents using a Java program. There are multiple libraries available that can be used to create tables inside PDFs using a Java program. However, they can be expensive, challenging to use, or have performance issues. It can be tricky to find a library that is easy to use, free for development, and performs effectively. IronPDF is one library that's very useful for manipulating PDF files. You can find more information about IronPDF by clicking on the IronPDF Official Java Page. The following steps are covered in this article: Create a new project Install IronPDF Library Create a new PDF document Create a table for it Add dynamic values to the PDF document Create a New Java Project Open your preferred IDE. IntelliJ is recommended in this article, so the steps to create a new project may differ using another IDE. Open IntelliJ IDE, click on File > New Project from the top menu bar. Name your project, select the location, language, build system, and JDK as shown below. IntelliJ IDE New Project Window Click on the Create Project button, and a new project will be created. Install IronPDF Library Now, install the IronPDF library in the newly created project. Continue with the following steps. Open the pom.xml file and add the necessary dependencies and repositories to use IronPDF. The specific content for the pom.xml is not provided in this article, but make sure to properly include the IronPDF library using Maven's dependency management. <!-- Add IronPDF dependencies here --> <dependencies> <!-- Example dependency for IronPDF, actual group and artifact id to be retrieved from official documentation --> <dependency> <groupId>com.ironsoftware</groupId> <artifactId>ironpdf</artifactId> <version>VERSION_NUMBER</version> </dependency> </dependencies> <!-- Add IronPDF dependencies here --> <dependencies> <!-- Example dependency for IronPDF, actual group and artifact id to be retrieved from official documentation --> <dependency> <groupId>com.ironsoftware</groupId> <artifactId>ironpdf</artifactId> <version>VERSION_NUMBER</version> </dependency> </dependencies> XML Type the following command into your terminal and press enter to install the specified Maven dependencies. mvn install mvn install SHELL This will install IronPDF in this project. Add the following import statement for using IronPDF classes. import com.ironsoftware.ironpdf.*; import com.ironsoftware.ironpdf.*; JAVA First of all, we will learn to create simple PDF documents in Java. Create a PDF document The following example code will create a new PDF document. public static void main(String[] args) throws IOException { // Create a PDF document from an HTML string PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("This is a sample PDF file"); try { // Save the created PDF document to a file myPdf.saveAs(Paths.get("html_saved.pdf")); } catch (IOException e) { throw new RuntimeException(e); } } public static void main(String[] args) throws IOException { // Create a PDF document from an HTML string PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("This is a sample PDF file"); try { // Save the created PDF document to a file myPdf.saveAs(Paths.get("html_saved.pdf")); } catch (IOException e) { throw new RuntimeException(e); } } JAVA The renderHtmlAsPdf method takes a string as an argument and converts that string into an instance of a PDF document. The saveAs function takes a file path as an argument and saves the newly created PDF document to the file path specified in the argument. A PDF is created from the above code, shown in the following image. New PDF Document Create table for the PDF file The following code will create a table in PDF. public static void main(String[] args) throws IOException { // HTML content for creating a table String tableContent = "<table>\n" + " <tr>\n" + " <th>Company</th>\n" + " <th>Contact</th>\n" + " <th>Country</th>\n" + " </tr>\n" + " <tr>\n" + " <td>Alfreds Futterkiste</td>\n" + " <td>Maria Anders</td>\n" + " <td>Germany</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Centro comercial Moctezuma</td>\n" + " <td>Francisco Chang</td>\n" + " <td>Mexico</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Ernst Handel</td>\n" + " <td>Roland Mendel</td>\n" + " <td>Austria</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Island Trading</td>\n" + " <td>Helen Bennett</td>\n" + " <td>UK</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Laughing Bacchus Winecellars</td>\n" + " <td>Yoshi Tannamuri</td>\n" + " <td>Canada</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Magazzini Alimentari Riuniti</td>\n" + " <td>Giovanni Rovelli</td>\n" + " <td>Italy</td>\n" + " </tr>\n" + "</table>"; // Create a PDF document with table content PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("<h1>Example of adding table in a PDF</h1>" + tableContent); try { // Save the created PDF document to a file myPdf.saveAs(Paths.get("html_saved.pdf")); } catch (IOException e) { throw new RuntimeException(e); } } public static void main(String[] args) throws IOException { // HTML content for creating a table String tableContent = "<table>\n" + " <tr>\n" + " <th>Company</th>\n" + " <th>Contact</th>\n" + " <th>Country</th>\n" + " </tr>\n" + " <tr>\n" + " <td>Alfreds Futterkiste</td>\n" + " <td>Maria Anders</td>\n" + " <td>Germany</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Centro comercial Moctezuma</td>\n" + " <td>Francisco Chang</td>\n" + " <td>Mexico</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Ernst Handel</td>\n" + " <td>Roland Mendel</td>\n" + " <td>Austria</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Island Trading</td>\n" + " <td>Helen Bennett</td>\n" + " <td>UK</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Laughing Bacchus Winecellars</td>\n" + " <td>Yoshi Tannamuri</td>\n" + " <td>Canada</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Magazzini Alimentari Riuniti</td>\n" + " <td>Giovanni Rovelli</td>\n" + " <td>Italy</td>\n" + " </tr>\n" + "</table>"; // Create a PDF document with table content PdfDocument myPdf = PdfDocument.renderHtmlAsPdf("<h1>Example of adding table in a PDF</h1>" + tableContent); try { // Save the created PDF document to a file myPdf.saveAs(Paths.get("html_saved.pdf")); } catch (IOException e) { throw new RuntimeException(e); } } JAVA The above code uses simple HTML tags to create a table in PDF using Java. So, to create a table, you must have basic knowledge of using HTML tags. Almost every Java programmer has knowledge of HTML, so it is very easy to create a new table and table cells using HTML tags. The PDF file generated by this program is shown in the following image: PDF document containing a table from HTML It's a simple table with no styling. Now let's add some styling to this table, such as set table width, margin, layout, font, background color, and more. Add Styling to the Table The following sample code will format our table and add styling to our cells. public static void main(String[] args) throws IOException { // HTML and CSS content for styling the table String htmlStyle = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "<style>\n" + "table {\n" + " font-family: arial, sans-serif;\n" + " border-collapse: collapse;\n" + " width: 100%;\n" + "}\n" + "\n" + "td, th {\n" + " border: 1px solid #dddddd;\n" + " text-align: left;\n" + " padding: 8px;\n" + "}\n" + "\n" + "tr:nth-child(even) {\n" + " background-color: #dddddd;\n" + "}\n" + "</style>\n" + "</head>\n" + "<body>"; String tableContent = "<table>\n" + " <tr>\n" + " <th>Company</th>\n" + " <th>Contact</th>\n" + " <th>Country</th>\n" + " </tr>\n" + " <tr>\n" + " <td>Alfreds Futterkiste</td>\n" + " <td>Maria Anders</td>\n" + " <td>Germany</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Centro comercial Moctezuma</td>\n" + " <td>Francisco Chang</td>\n" + " <td>Mexico</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Ernst Handel</td>\n" + " <td>Roland Mendel</td>\n" + " <td>Austria</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Island Trading</td>\n" + " <td>Helen Bennett</td>\n" + " <td>UK</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Laughing Bacchus Winecellars</td>\n" + " <td>Yoshi Tannamuri</td>\n" + " <td>Canada</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Magazzini Alimentari Riuniti</td>\n" + " <td>Giovanni Rovelli</td>\n" + " <td>Italy</td>\n" + " </tr>\n" + "</table>\n</body>\n" + "</html>"; // Create a PDF document with styled table content PdfDocument myPdf = PdfDocument.renderHtmlAsPdf(htmlStyle + "Sample PDF" + tableContent); try { // Save the created PDF document to a file myPdf.saveAs(Paths.get("html_saved.pdf")); } catch (IOException e) { throw new RuntimeException(e); } } public static void main(String[] args) throws IOException { // HTML and CSS content for styling the table String htmlStyle = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "<style>\n" + "table {\n" + " font-family: arial, sans-serif;\n" + " border-collapse: collapse;\n" + " width: 100%;\n" + "}\n" + "\n" + "td, th {\n" + " border: 1px solid #dddddd;\n" + " text-align: left;\n" + " padding: 8px;\n" + "}\n" + "\n" + "tr:nth-child(even) {\n" + " background-color: #dddddd;\n" + "}\n" + "</style>\n" + "</head>\n" + "<body>"; String tableContent = "<table>\n" + " <tr>\n" + " <th>Company</th>\n" + " <th>Contact</th>\n" + " <th>Country</th>\n" + " </tr>\n" + " <tr>\n" + " <td>Alfreds Futterkiste</td>\n" + " <td>Maria Anders</td>\n" + " <td>Germany</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Centro comercial Moctezuma</td>\n" + " <td>Francisco Chang</td>\n" + " <td>Mexico</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Ernst Handel</td>\n" + " <td>Roland Mendel</td>\n" + " <td>Austria</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Island Trading</td>\n" + " <td>Helen Bennett</td>\n" + " <td>UK</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Laughing Bacchus Winecellars</td>\n" + " <td>Yoshi Tannamuri</td>\n" + " <td>Canada</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Magazzini Alimentari Riuniti</td>\n" + " <td>Giovanni Rovelli</td>\n" + " <td>Italy</td>\n" + " </tr>\n" + "</table>\n</body>\n" + "</html>"; // Create a PDF document with styled table content PdfDocument myPdf = PdfDocument.renderHtmlAsPdf(htmlStyle + "Sample PDF" + tableContent); try { // Save the created PDF document to a file myPdf.saveAs(Paths.get("html_saved.pdf")); } catch (IOException e) { throw new RuntimeException(e); } } JAVA The added CSS is used for styling the table in the PDF. Hence, it is very efficient to use CSS for styling as needed. Following is the PDF generated by this program. PDF document containing a table from HTML and styled with CSS This above code looks very messy. But it can be cleaned by moving all the HTML content into an HTML file and then generating the PDF from that file. Create a table using an HTML file in PDF using Java Create a new HTML file and add all your HTML content to that file as shown below: HTML moved into its own HTML file Add the following code to the Java program. // Create a PDF document from an HTML file PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("Create_Table.html"); try { // Save the created PDF document to a file myPdf.saveAs(Paths.get("html_saved.pdf")); } catch (IOException e) { throw new RuntimeException(e); } // Create a PDF document from an HTML file PdfDocument myPdf = PdfDocument.renderHtmlFileAsPdf("Create_Table.html"); try { // Save the created PDF document to a file myPdf.saveAs(Paths.get("html_saved.pdf")); } catch (IOException e) { throw new RuntimeException(e); } JAVA We can see how easy it is to generate a PDF using an HTML document. If you need to create PDF files in Java, the easiest way is to create a separate HTML document with content and styling and then just convert your HTML document into PDF with a single line of code. Final PDF document with styling Summary This tutorial demonstrated how to create a styled table in a PDF file using Java and learned to convert HTML files into PDF files. IronPDF for Java also offers functionality to add images to the PDF file, split PDF files, add headers and footers, apply digital signatures, and much more. Explore IronPDF Documentation to learn more about these features and additional capabilities. Remove the IronPDF watermark from your generated PDF documents by purchasing a license key or by registering for a free trial. Preguntas Frecuentes ¿Cómo puedo comenzar un nuevo proyecto Java para crear PDFs? Para iniciar un nuevo proyecto Java para crear PDFs, puedes usar un IDE como IntelliJ. Comienza configurando el proyecto e instalando la biblioteca IronPDF a través de Maven para manejar la creación y manipulación de PDFs. ¿Qué pasos están involucrados en convertir contenido HTML a PDF en Java? Para convertir contenido HTML a PDF en Java, puedes usar el método PdfDocument.renderHtmlAsPdf de IronPDF. Esto implica escribir tu contenido HTML, opcionalmente estilizarlo con CSS y renderizarlo en un PDF. ¿Puedo usar CSS para dar estilo a tablas en PDFs generados con Java? Sí, puedes usar CSS para dar estilo a tablas en PDFs al incluir el CSS dentro del contenido HTML antes de renderizarlo en un PDF usando IronPDF. Esto te permite definir fuentes, bordes, colores y más. ¿Cómo creo un PDF a partir de un archivo HTML externo usando Java? Para crear un PDF a partir de un archivo HTML externo en Java, puedes usar el método PdfDocument.renderHtmlFileAsPdf de IronPDF, que convierte todo el archivo HTML en un documento PDF. ¿Cuáles son los beneficios de usar una biblioteca de terceros para la creación de PDFs en Java? Usar una biblioteca de terceros como IronPDF simplifica el proceso de creación de PDFs en Java, ofreciendo características como conversión de HTML a PDF, estilo de tablas, y funcionalidades adicionales como soporte para imágenes y firmas digitales. ¿Cómo puedo incluir imágenes en un documento PDF usando bibliotecas Java? Puedes incluir imágenes en un documento PDF incorporándolas dentro del contenido HTML que renderizas en un PDF usando IronPDF. Este método permite la incorporación fluida de elementos visuales. ¿Qué opciones hay disponibles para dividir PDFs en Java? IronPDF ofrece opciones para dividir PDFs, permitiéndote dividir un único PDF en múltiples documentos. Esta característica puede ser particularmente útil para gestionar documentos grandes o extraer secciones específicas. ¿Cómo puedo aplicar firmas digitales a PDFs usando Java? Puedes aplicar firmas digitales a PDFs usando las características integradas de IronPDF, que soportan la adición de firmas digitales para mejorar la seguridad y autenticidad del documento. ¿Qué debo hacer si hay una marca de agua en mis documentos PDF? Si hay una marca de agua en tus documentos PDF creados con IronPDF, puedes eliminarla comprando una clave de licencia o registrándote para una licencia de prueba gratuita. Darrius Serrant Chatea con el equipo de ingeniería ahora Ingeniero de Software Full Stack (WebOps) Darrius Serrant tiene una licenciatura en Ciencias de la Computación de la Universidad de Miami y trabaja como Ingeniero de Marketing WebOps Full Stack en Iron Software. Atraído por la programación desde joven, vio la computación como algo misterioso y accesible, convirtiéndolo en el ...Leer más Artículos Relacionados Actualizadojunio 22, 2025 Cómo Convertir TIFF A PDF en Java Esta guía integral te llevará a través de los pasos sobre cómo convertir imágenes TIFF a PDF sin problemas en Java usando IronPDF. Leer más Actualizadojulio 28, 2025 Cómo Convertir PDF a PDFA en Java En este artículo, exploraremos cómo convertir archivos PDF al formato PDF/A en Java usando IronPDF. Leer más Actualizadojulio 28, 2025 Cómo Crear Un Documento PDF en Java Este artículo proporcionará una guía integral para trabajar con PDFs en Java, cubriendo conceptos clave, la mejor biblioteca y ejemplos. Leer más Cómo Convertir PNG a PDF en Java (Tutorial)Creador de PDF Para Java (Tutorial ...
Actualizadojunio 22, 2025 Cómo Convertir TIFF A PDF en Java Esta guía integral te llevará a través de los pasos sobre cómo convertir imágenes TIFF a PDF sin problemas en Java usando IronPDF. Leer más
Actualizadojulio 28, 2025 Cómo Convertir PDF a PDFA en Java En este artículo, exploraremos cómo convertir archivos PDF al formato PDF/A en Java usando IronPDF. Leer más
Actualizadojulio 28, 2025 Cómo Crear Un Documento PDF en Java Este artículo proporcionará una guía integral para trabajar con PDFs en Java, cubriendo conceptos clave, la mejor biblioteca y ejemplos. Leer más
Producto completamente funcional Obtén 30 días de producto completamente funcional.Instálalo y ejecútalo en minutos.
Soporte técnico 24/5 Acceso completo a nuestro equipo de soporte técnico durante tu prueba del producto
Producto completamente funcional Obtén 30 días de producto completamente funcional.Instálalo y ejecútalo en minutos.
Soporte técnico 24/5 Acceso completo a nuestro equipo de soporte técnico durante tu prueba del producto