Printing Multiple JTable in a PDF using itext - java

I am trying to print two JTable in a PDF file, here is what I tried but is printing only the headers of the column, please how will I add the content of the table.
try{
Document document = new Document();
PdfWriter.getInstance(document,new FileOutputStream("transcript.pdf"));
document.open();
document.add(new Paragraph("UNIVERSITY OF MAIDUGURI"));
document.add(new Paragraph("======================================================================="));
PdfPTable table1 = new PdfPTable(partITable.getColumnCount());
PdfPTable table2 = new PdfPTable(partITable2.getColumnCount());
table1.setSpacingAfter(10);
table1.setSpacingBefore(5);
for(int i=0;i<partITable.getColumnCount();i++){
table1.addCell(partITable.getColumnName(i));
}
for(int rows=0;rows<partITable.getRowCount()-1;rows++){
for(int cols=0;cols<partITable.getColumnCount();cols++){
table1.addCell(partITable.getModel().getValueAt(rows,cols).toString());
}
}
for(int i=0;i<partITable2.getColumnCount();i++){
table2.addCell(partITable2.getColumnName(i));
}
for(int rows=0;rows<partITable2.getRowCount()-1;rows++){
for(int cols=0;cols<partITable2.getColumnCount();cols++){
table2.addCell(partITable2.getModel().getValueAt(rows,cols).toString());
}
}
document.add(table1);
document.add(table2);
document.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}

You have a logic error. I guess that you have following situation: partITable.getRowCount() = partITable2.getRowCount() = 1. Because you set the upper bound to partITable.getRowCount() - 1 = 0, the condition of the for loop returns false, which implies that the body of the for loop will be never executed.
Summarized you have to set the upper bound to partITable.getRowCount()

Related

I am trying to write data by rows using for loop, There regularly i need to change data For that i am doing paramerization

I am trying to write multiple data in excel by iterating rows, Some times it's working fine , Some times it's not. I want to iterate upto 12 rows , Every time that grouID will get changes. Some time it's replacing data and some time it's throwing an error as can't get numeric value from text
public void writeData(String GroupID) {
try {
File src = new File("File.xls");
Cell cell = null;
FileInputStream fis = new FileInputStream(src);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sh1 = wb.getSheetAt(0);
for (int i = 1; i < 12; i++) {
System.out.println("Entering into excel sheet");
cell = sh1.getRow(i).getCell(22);
System.out.println("Iterating cells");
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
String str = NumberToTextConverter.toText(cell.getNumericCellValue());
System.out.println("**********Before Replacing**********");
System.out.println(str);
cell.setCellValue(GroupID);
} else {
System.out.println("We are not entering numeric data");
}
}
FileOutputStream fout = new FileOutputStream(new File("File.xls"));
wb.write(fout);
fout.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
In order to avoid exception, you need to check the cell type before accessing its value. In your scenario, it seems some times the cell does not contain a numeric value. So, invoke getCellType() on the cell and based on its return type (String or Number) invoke appropriate methods (for String - getStringCellValue() and for Number - getNumericCellValue())

Apache POI writes only one record

I am writing some data into excel file using Apache POI but for some reason the file shows only the last record (1 record only). I have list of POLJO that I am passing. I am also iterating through the cells but all I get is just one record.
Method to write in excel
public void writeToExcel(List<NYProgramTO> to){
try {
Workbook workBook = new HSSFWorkbook();
CreationHelper helper = workBook.getCreationHelper();
Sheet sheet = workBook.createSheet("NY_PPA_P3_Sheet");
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("First Name");
headerRow.createCell(1).setCellValue("Last Name");
headerRow.createCell(2).setCellValue("Policy Number");
headerRow.createCell(3).setCellValue("Zip Code");
headerRow.createCell(4).setCellValue("Date of Birth");
if(to != null){
int size = to.size();
for(int i = 0; i < size; i++){
NYProgramTO nyP= to.get(i);
Row row = sheet.createRow(1);
row.createCell(0).setCellValue(nyP.getFirstName());
row.createCell(1).setCellValue(nyP.getLastName());
row.createCell(2).setCellValue(nyP.getPolicyNumber());
row.createCell(3).setCellValue(nyP.getZipCode());
row.createCell(4).setCellValue(nyP.getDateOfBirth());
}
}
FileOutputStream stream = new FileOutputStream("NY_PPA_P3.xlsx");
workBook.write(stream);
stream.close();
System.out.println("NY_PPA_P3.xlsx created successfully.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
If by "only one record" you mean that only one row is appearing, this is probably easily fixable by making sure that you increment the Row that is being created before writing the Cells.
Try changing:
Row row = sheet.createRow(1);
to:
Row row = sheet.createRow(i+1);

iText - Creating PDF with one small table and one large table causes the large table to move to new Page instead of splitting

I'm trying to create a PDF using some data. The data was represented using tables. There are 2 tables.
One table is with 5 rows and 3 columns occupying almost half of the PDF page 1. The other table is having 50 rows and 3 columns which are getting created in a new page (on page 2) instead of continuing after the 1st table on page 1.
How to make the PDF to create the 2nd table under the first table on page 1 and continue to page 2 if the second table has more rows. Should I use PdfPageEvent?
public static void createPDF() throws IOException {
Document document = new Document();
PdfWriter pdfWriter = null;
String fileName = "temp.pdf";
try {
filePath = tempDirPath + File.separator + fileName;
FileOutputStream fos = new FileOutputStream(filePath);
pdfWriter = PdfWriter.getInstance(document, fos);
document.open();
document.add(addTitleTable());
document.add(addObjsTable());
document.add(addDateTable());
document.close();
pdfWriter.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
document.close();
pdfWriter.close();
}
}
Your problem can not be reproduced.
I have created this example:
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
// Table 1
PdfPTable table = new PdfPTable(3);
table.setSpacingAfter(10);
for(int i = 1; i <= 15; i++){
table.addCell("Cell " + i);
}
document.add(table);
table = new PdfPTable(3);
for(int i = 1; i <= 150; i++){
table.addCell("Cell " + i);
}
document.add(table);
document.close();
}
First we create a table with 3 columns and 5 rows (15 cells in total). We define a small spacing after the table of 10 user units.
Then we create a table with 3 columns and 50 rows (150 cells in total).
We add both tables to the document, one after the other. The result looks like this:
I have followed all the instructions you shared in your question, and the result I obtained shows that your allegation that the second tables starts on a new page is false. The second table starts on the same page as the first table. There's a gap of 10 user units between both tables (as defined in our code). Maybe there is a problem with your code, but please understand that no one can help you if no one can reproduce the problem.

When i am generating pdf form I want to add form number on top left of the pdf using itext java

Hi When I am generating form using java with itext I want to add form number on top left of the document
above the header.Please let me know the ways to do it.
PdfPTable table = new PdfPTable(3); // 3 columns.
table.setWidthPercentage(100);
PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
cell1.setBorder(0);
cell2.setBorder(0);
cell3.setBorder(0);
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
How can I set the table alignment to start of the page margin.
Your question is very confusing. You say you are creating a form, but when you say form, you don't seem to be referring to an interactive form, but to an ordinary PDF containing a table.
You say you want to add a number above the header, but you are not telling us what you mean by header. You are assuming that the people reading your question can read your mind.
I guess you want to use a page event to add a String in the top left corner of each page. That would make your question almost a duplicate of itextsharp: How to generate a report with dynamic header in PDF using itextsharp?
You can create a subclass of PdfPageEventHelper like this:
public class Header extends PdfPageEventHelper {
protected Phrase header;
public void setHeader(Phrase header) {
this.header = header;
}
#Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte canvas = writer.getDirectContentUnder();
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, header, 36, 806, 0);
}
}
You can then use this Header class like this:
public void createPdf(String filename) throws IOException, DocumentException {
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
Header event = new Header();
writer.setPageEvent(event);
// step 3
document.open();
// step 4
List<Integer> factors;
for (int i = 2; i < 301; i++) {
factors = getFactors(i);
if (factors.size() == 1) {
document.add(new Paragraph("This is a prime number!"));
}
for (int factor : factors) {
document.add(new Paragraph("Factor: " + factor));
}
event.setHeader(new Phrase(String.format("THE FACTORS OF %s", i)));
document.newPage();
}
// step 5
document.close();
}
In your case, you wouldn't have:
event.setHeader(new Phrase(String.format("THE FACTORS OF %s", i)));
You'd have something like:
event.setHeader(new Phrase(number));
Where number is the number you want to add at the coordinate x = 36, y = 806.

Inserting greater than or equal symbol in to an iText PDF, ie >=

Does anyone know an easy way to include the greater than or equal symbol in an iText PDF document without resorting to custom fonts?
You need to add the unicode for this character. Also make sure that the char is included in the font you use.
document.add( new Paragraph("\u2265"));
Use the below code for the same. It's work for me.
//symbol for greater or equal then
public void process() throws DocumentException, IOException {
String dest = "/home/ashok/ashok/tmp/hello.pdf";
BaseFont bfont = BaseFont.createFont(
"/home/ashok/ashok/fonts/Cardo-Regular.ttf",
BaseFont.IDENTITY_H,
BaseFont.EMBEDDED);
Font font = new Font(bfont, 12);
try {
Document document=new Document();
PdfWriter.getInstance(document,new
FileOutputStream("/home/ashok/ashok/tmp/hello.pdf"));
document.open();
Chunk chunk = new Chunk("\u2265");
Paragraph p = new Paragraph("Mathematical Operators are ",font);
p.add(chunk);
document.add(p);
p = new Paragraph(" ",font);
chunk = new Chunk("\u2264");
p.add(chunk);
document.add(p);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Categories