Add Table to PDF Example
This program demonstrates adding a table into a PDF file.
Problem Statement
Write a Java program that creates a simple table in a PDF file using PDFBox.
Source Code
| 1 | import java.io.*; |
| 2 | import org.apache.pdfbox.pdmodel.*; |
| 3 | import org.apache.pdfbox.pdmodel.font.*; |
| 4 | public class AddTablePDFExample { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq Add Table PDF Example"); |
| 7 | try(PDDocument doc=new PDDocument()) { |
| 8 | PDPage page=new PDPage(); |
| 9 | doc.addPage(page); |
| 10 | PDPageContentStream cs=new PDPageContentStream(doc,page); |
| 11 | cs.beginText(); |
| 12 | cs.setFont(PDType1Font.HELVETICA,12); |
| 13 | cs.newLineAtOffset(100,700); |
| 14 | cs.showText("ID Name Country"); |
| 15 | cs.newLineAtOffset(0,-20); |
| 16 | cs.showText("1 Arun India"); |
| 17 | cs.newLineAtOffset(0,-20); |
| 18 | cs.showText("2 Priya USA"); |
| 19 | cs.endText(); |
| 20 | cs.close(); |
| 21 | doc.save("table.pdf"); |
| 22 | System.out.println("Eduinq Table Added Successfully"); |
| 23 | } catch(IOException e) { |
| 24 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 25 | } |
| 26 | } |
| 27 | } |
Program Output
Eduinq Add Table PDF Example Eduinq Table Added Successfully
Explanation
Tables simulated using text alignment. - PDFBox does not have native table support, but text placement works. - Exception handling ensures safe operations. - In enterprise systems, tables are used for structured reports. Conclusion: Shows adding tables to PDF files.