-4
  • Hi Every One
  • I've a pdf report generated with iText containing a PdfPTable added to MultiColumnText, sometimes becomes so large that it will be split on more than one page,
  • Here am added sample Code, Its working as

Page -1

--------------------------------------------------------------------------------------------------------------------------------------------------+ | 1st - Emp1-NO | 2nd - Emp1-Name| 3rd - Emp1-Desig |

| 4th - Emp2-NO | 5th - Emp2-Name| 6th - Emp2-Desig |

| 7th - Emp3-NO | 8th - Emp3-Name| 9th - Emp3-Desig |

--------------------------------------------------------------------------------------------------------------------------------------------------+

  • but i want fill the data as first No all rows then each columns i.e. column by column

  • Like below

Page -1

--------------------------------------------------------------------------------------------------------------------------------------------------+ | 1st - Emp1-NO | 4th - Emp1-Name| 7th - Emp1-Desig |

| 2nd - Emp2-NO | 5th - Emp2-Name| 8th - Emp2-Desig |

| 3rd - Emp3-NO | 6th - Emp3-Name| 9th - Emp3-Desig |

--------------------------------------------------------------------------------------------------------------------------------------------------+

**My Code is **

package com.ace.pdf;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPage;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

public class AttendanceTimeSheet {
    public static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, BaseColor.BLACK);
    public static Font subSecFont = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD, BaseColor.BLUE);
    public static Font tableCellFont = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD);
    public static Font smallFont = new Font(Font.FontFamily.TIMES_ROMAN, 6, Font.NORMAL);
    public static Font smallFontofnames = new Font(Font.FontFamily.TIMES_ROMAN, 7, Font.BOLD);
    public static Font smallFontofcomp = new Font(Font.FontFamily.TIMES_ROMAN, 7, Font.BOLD);
    public static Font smallFontofstopped = new Font(Font.FontFamily.TIMES_ROMAN, 7, Font.BOLD);
    public static Font smallFontofGPS = new Font(Font.FontFamily.TIMES_ROMAN, 7, Font.BOLD);
    public static Font smallWhiteFont = new Font(Font.FontFamily.TIMES_ROMAN, 6, Font.NORMAL);
    public static Font smallFontUnderline = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL);
    public static Font smallHeadersFont = new Font(Font.FontFamily.TIMES_ROMAN, 7, Font.BOLD);
    public static Font FontForAllBold = new Font(Font.FontFamily.TIMES_ROMAN, 7, Font.BOLD);

    public static Font headerBold = new Font(Font.FontFamily.TIMES_ROMAN, 5, Font.BOLD);
    public static Font headerBoldData = new Font(Font.FontFamily.TIMES_ROMAN, 5, Font.BOLD);

    public class Rotate extends PdfPageEventHelper {
        protected PdfNumber rotation = PdfPage.PORTRAIT;

        public void setRotation(PdfNumber rotation) {
            this.rotation = rotation;
        }

        public void onEndPage(PdfWriter writer, Document document) {
            //writer.addPageDictEntry(PdfName.ROTATE, rotation);
        }
    }

    public static void main(String[] args) throws IOException, DocumentException {
        new AttendanceTimeSheet().createPdf();
    }

    public void createPdf() throws IOException, DocumentException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Rectangle pagesize = new Rectangle(842f, 595f);
        Document document = new Document(pagesize, 10f, 10f, 10f, 10f);
        try {
            OutputStream file = new FileOutputStream(new File("E:\\ExamplePDF\\AttSheet+" + new Date().getTime() + ".pdf"));
            PdfWriter writer = PdfWriter.getInstance(document, file);
            Rotate rotation = new Rotate();
            writer.setPageEvent(rotation);
            rotation.setRotation(PdfPage.SEASCAPE);
            document.open();
            Paragraph paraRepName = new Paragraph();
            paraRepName.add(new Paragraph("SHEET", catFont));
            paraRepName.setSpacingAfter(04);
            document.add(paraRepName);
            int pageNo = 1;
            PdfPTable headeTable = headerTable_Main();
            document.add(headeTable);           
            PdfPTable data_HeadeTable = headerTable_Data();
            document.add(data_HeadeTable);
            for (int rows = 1; rows <= 10; rows++) {
                //Here will dynamic data some List
                PdfPTable rdTable = rawDataTable();
                document.add(rdTable);
            }
            document.newPage();
            pageNo = pageNo + 1;
            Paragraph balnkParaSummary = new Paragraph();
            document.add(balnkParaSummary);
            document.close();
            System.out.println("Pdf created successfully..");
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    private static PdfPTable headerTable_Main() throws DocumentException {
        PdfPTable table = new PdfPTable(7);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 20, 40, 10, 10, 10, 10, 10 });
        PdfPCell cell = new PdfPCell();
        for (int tblrow = 1; tblrow <= 3; tblrow++) {
            String cellHead1 = "";
            String cellHead2 = "";
            String cellHead3 = "";
            String cellHead4 = "";
            String cellHead5 = "";
            String cellHead6 = "";
            String cellHead7 = "";
            if (tblrow == 1) {
                cellHead1 = "Project : ACE";
                cellHead2 = "";
                cellHead3 = "Legend:";
                cellHead4 = "AB = Absent";
                cellHead5 = "R = Rest Day";
                cellHead6 = "O = Off Day";
                cellHead7 = "H = Holi Day";
            } else if (tblrow == 2) {
                cellHead1 = "CLIENT : DOPMO";
                cellHead2 = "";
                cellHead3 = "";
                cellHead4 = "AL = Annual Leave";
                cellHead5 = "EL = Emg Leave";
                cellHead6 = "L1 = ";
                cellHead7 = "L2 = ";
            } else {
                cellHead1 = "Period : ";
                cellHead2 = "";
                cellHead3 = "";
                cellHead4 = "";
                cellHead5 = "";
                cellHead6 = "";
                cellHead7 = "";
            }

            for (int i = 1; i <= 7; i++) {
                if (i == 1) {
                    cell = new PdfPCell(new Phrase(cellHead1, headerBold));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                } else if (i == 2) {
                    cell = new PdfPCell(new Phrase(cellHead2, headerBold));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                } else if (i == 3) {
                    cell = new PdfPCell(new Phrase(cellHead3, headerBold));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                } else if (i == 4) {
                    cell = new PdfPCell(new Phrase(cellHead4, headerBold));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                } else if (i == 5) {
                    cell = new PdfPCell(new Phrase(cellHead5, headerBold));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                } else if (i == 6) {
                    cell = new PdfPCell(new Phrase(cellHead6, headerBold));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                } else {
                    cell = new PdfPCell(new Phrase(cellHead7, headerBold));
                    cell.setHorizontalAlignment(Element.ALIGN_LEFT);
                }
                if (i <= 3 || tblrow == 3) {
                    cell.setBorderWidthRight(0);
                    cell.setBorderWidthLeft(0);
                    cell.setBorderWidthTop(0);
                    cell.setBorderWidthBottom(0);
                    cell.setBorderColorBottom(BaseColor.WHITE);
                    cell.setBorderColorLeft(BaseColor.WHITE);
                    cell.setBorderColorRight(BaseColor.WHITE);
                    cell.setBorderColorTop(BaseColor.WHITE);
                }
                cell.setBackgroundColor(BaseColor.WHITE);
                cell.setFixedHeight(8);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setUseAscender(true);
                table.addCell(cell);
            }
        }

        return table;
    }

    private static PdfPTable headerTable_Data() throws DocumentException {
        PdfPTable table = new PdfPTable(33);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 10, 10, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02,
                02, 02, 02, 02, 02 });
        table.setSpacingBefore(05.0f);  
        PdfPCell cell = new PdfPCell();
        Date currentDate = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(currentDate);
        for (int tblRow = 1; tblRow <= 2; tblRow++) {
            currentDate = new Date();
            cal = Calendar.getInstance();
            cal.setTime(currentDate);
            int dateNo = 1;
            int dateNos = 1;
            for (int i = 1; i <= 33; i++) {
                cal.set(Calendar.DATE, dateNos);
                if (i == 1) {
                    if (tblRow != 1) {
                        cell = new PdfPCell(new Phrase("Name", smallHeadersFont));
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    }
                } else if (i == 2) {
                    if (tblRow != 1) {
                        cell = new PdfPCell(new Phrase("Role", smallHeadersFont));
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    }
                } else {
                    if (tblRow == 1) {
                        if (i >= 3) {
                            cell = new PdfPCell(new Phrase(cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US), headerBold));
                            if(cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US) == "Fri"){
                                cell.setBackgroundColor(BaseColor.BLUE);
                            }else{
                                cell.setBackgroundColor(BaseColor.WHITE);
                            }
                            dateNos = dateNos + 1;
                        }
                    } else {
                        cell = new PdfPCell(new Phrase("" + dateNo, headerBold));
                        if(cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US) == "Fri"){
                            cell.setBackgroundColor(BaseColor.BLUE);
                        }else{
                            cell.setBackgroundColor(BaseColor.WHITE);
                        }
                        dateNo = dateNo + 1;
                        dateNos = dateNos + 1;
                    }

                }
                cell.setFixedHeight(15);
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setUseAscender(true);
                table.addCell(cell);

            }
        }

        return table;
    }

    private static PdfPTable rawDataTable() throws DocumentException {

        PdfPTable table = new PdfPTable(33);
        table.setWidthPercentage(100);
        table.setWidths(new int[] { 10, 10, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02, 02,
                02, 02, 02, 02, 02 });
        table.setSpacingBefore(0.0f);
        String head1;
        String head2;
        Date currentDate = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(currentDate);

        for (int j = 1; j <= 2; j++) {
            currentDate = new Date();
            cal = Calendar.getInstance();
            cal.setTime(currentDate);
            if (j == 1) {
                head1 = "Rajinikanth Developer";
                head2 = "Designation ";
            } else {
                head1 = "";
                head2 = "";
            }
            PdfPCell cell = new PdfPCell();
            int dateNos = 1;
            for (int i = 1; i <= 33; i++) {
                cal.set(Calendar.DATE, dateNos);

                if (i == 1) {
                    if (j == 2) {
                        cell = new PdfPCell(new Phrase("10:12", headerBoldData));
                        dateNos = dateNos + 1;
                    } else {
                        cell = new PdfPCell(new Phrase(head1, headerBoldData));
                    }
                } else if (i == 2) {
                    if (j == 2) {
                        cell = new PdfPCell(new Phrase("10:13", headerBoldData));
                        dateNos = dateNos + 1;
                    } else {
                        cell = new PdfPCell(new Phrase(head2, headerBoldData));
                    }
                } else {
                    if (j == 1) {
                        cell = new PdfPCell(new Phrase("10:11", headerBoldData));
                        dateNos = dateNos + 1;

                    } else {
                        cell = new PdfPCell(new Phrase("08:59", headerBoldData));
                        dateNos = dateNos + 1;
                    }

                }
                if (j == 1 && i <= 2) {
                    cell.setRowspan(2);
                }
                cell.setFixedHeight(15);
                if(cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US) == "Fri"){
                    cell.setBackgroundColor(BaseColor.BLUE);
                }else{
                    cell.setBackgroundColor(BaseColor.WHITE);
                }
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                cell.setUseAscender(true);
                table.addCell(cell);

            }

        }

        return table;
    }
}

**sample PDF is ** SamplePDF

Question Updating

  1. I have 150 Employees Data

  2. Each Employee Have Name & InTime & OutTime

  3. Please find the PDF Image

  4. I Need Help on Logic of cell fill as a. Print Employee Ids in 1st Column - 150 employees b. Then already printed each row 2nd Column with Employee Name c. Then print with In time 3rd Column

Simply From PDFIMAGE- First Print 3 rows with 1st Column [1066,1067,1069] Ids Then again Print again Exiting 3 rows 2nd Column[Name-ABCD, Name-XYZ, Name-PQR]..etc

    ConcurrentHashMap<String,EmpHistory> emp_HistoryList = new ConcurrentHashMap<String, EmpHistory>();
emp_HistoryList = this.getHistoryData();
for(EmpInfo emp : empInfoList){
    empHistory = emp_HistoryList.get(emp.getId());
    //Print all 105 Emps rows with IDs in 1st Column
    //Print each Emp row Name and IN time column
}

Question Update - 2

  • I am using Java with iText
  • I need to put text in columns,
  • I Created PDFTable as : PdfPTable table = new PdfPTable(33);
  • The problem is that PdfPTable fills the table row by row, that is, you first give the cell in column 1 of row 1, then column 2 of row 1, and so on, but I need to do it column by column, because that is how the data is being fed to me.

I Need Like as :

1 3 5 2 4 6

  • present code working as

1 2 3 4 5 6

  • please may i know where i did changes from my example code
  • please help on this, thanks in Advance.
kks
  • 342
  • 5
  • 25
  • [1] You are using iText 5 (`com.itextpdf`), but you mention `MultiColumnText`. `MultiColumnText` doesn't exist in iText 5 and I can't find it in your long code snippet anyway. [2] What is the screen shot about? It looks OK, but I don't understand how it relates to your question. Is that the desired output? If not, what is wrong with it? (It's too small to be legible.) Your code is too long for anyone to read. Please rephrase your question in simple words. Now you are just confusing people. – Bruno Lowagie May 30 '16 at 14:51
  • thanks @BrunoLowagie, simply [1] i have EmpInfo List Its have 105 Objects, am Iterating 105 EmpInfo Objets, and Each Emp Have 3 HistoryRecordsData. `ConcurrentHashMap emp_HistoryList = new ConcurrentHashMap(); emp_HistoryList = this.getHistoryData(); for(EmpInfo emp : empInfoList){ empHistory = emp_HistoryList.get(emp.getId()); //Print all 105 Emps rows with IDs in 1st Column //Print each Emp row Name and IN time column }` – kks May 30 '16 at 16:44
  • 1
    Please update your question instread of copy/pasting code in a comment section. Also: it's still not clear what you're trying to do. Please explain it as if you're talking to someone who doesn't know your requirement. – Bruno Lowagie May 30 '16 at 17:19
  • Thanks @BrunoLowagie, sorry for confusing, I have Updated my Requirement, – kks May 30 '16 at 18:04
  • @BrunoLowagie, I am using Java with iText, I need to put text in columns, so I am trying to use PdfPTable. I create it with:`PdfPTable table = new PdfPTable(33);`. The problem is that PdfPTable fills the table row by row, that is, you first give the cell in column 1 of row 1, then column 2 of row 1, and so on, but I need to do it column by column, because that is how the data is being fed to me. i need to fill data as `1 3 5
    2 4 6`
    – kks Jun 01 '16 at 05:34
  • This is a non-issue that any self-respecting developer can solve: create some kind of matrix first. Fill that matrix the way you want to. Then create the `PdfPTable` row by row. It's as simple as that. – Bruno Lowagie Jun 01 '16 at 05:56
  • Thanks @BrunoLowagie, Present code working fine with Row By Row, But need Column by Column, can you provide some sample or example or edit my code, its very helpfull. I have updated in Question as **Question Update-2** – kks Jun 01 '16 at 06:28
  • Are you saying that you're not able to create a two-dimensional array? – Bruno Lowagie Jun 01 '16 at 06:36
  • Thanks @BrunoLowagie, I know but i am confusing the same implementation creating of PDFTable and Cell and adding its table to document. **for two-dimensional** `int array[][] = new int[3][]; array[0] = new int[3]; array[1] = new int[2]; array[2] = new int[5];` – kks Jun 01 '16 at 06:42
  • 1
    You are indeed very confusing. You ask a question as if it's an iText question, but in reality, it's a simple programming question that isn't really related to iText. I'll create an answer that explains the elementary Math that is needed to solve your problem. Please consider taking a Math class. – Bruno Lowagie Jun 01 '16 at 07:21
  • Please read tag descriptions before adding tags. I removed [java-ee] tag from your question for second time. Thank you. – BalusC Jun 01 '16 at 07:23
  • @BalusC It's actually a simple question about two-dimensional arrays. I have no idea why the OP insists that it's a [java-ee] question. – Bruno Lowagie Jun 01 '16 at 07:33

2 Answers2

4

For logical reasons, tables are filled row by row in iText:

enter image description here

If you want to change the order, you need to do this yourself by creating a data matrix first. One way to do this, is by creating a two-dimensional array (there are other ways, but I'm using an array for the sake of simplicity).

The RowColumnOrder example shows how it's done.

This is the normal behavior:

document.add(new Paragraph("By design tables are filled row by row:"));
PdfPTable table = new PdfPTable(5);
table.setSpacingBefore(10);
table.setSpacingAfter(10);
for (int i = 1; i <= 15; i++) {
    table.addCell("cell " + i);
}
document.add(table);

You want to change this behavior, which means that you have to create a matrix in which you change the order rows and columns are filled:

String[][] array = new String[3][];
int column = 0;
int row = 0;
for (int i = 1; i <= 15; i++) {
    if (column == 0) {
        array[row] = new String[5];
    }
    array[row++][column] = "cell " + i;
    if (row == 3) {
        column++;
        row = 0;
    }
}

As you can see, there is no iText code involved. I have 15 cells to add in a table with 5 columns and 3 rows. To achieve this, I create a String[3][5] array of which I fill every row of a column, then switch to the next column when the current column is full. Once I have the two-dimensional matrix, I can use it to fill a PdfPTable:

table = new PdfPTable(5);
table.setSpacingBefore(10);
for (String[] r : array) {
    for (String c : r) {
        table.addCell(c);
    }
 }
 document.add(table);

As you can see, the second table in row_column_order.pdf gives you the result you want.

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • 2
    @kks I see that you opened a bounty on this question after I answered it. What in my answer don't you understand? What isn't clear? I posted a screen shot of the situation you experience and the situation you desire. That screen shot was taken from a PDF created with the code sample that explains you how to get the desired result. What more do you need? You claim that "the current answers do not contain enough detail." That's unbelievable. My answer is extremely detailed! – Bruno Lowagie Jun 03 '16 at 12:41
  • 1
    @ Bruno Lowagie : Nice Explanation, i think **@KKS** wants code using of **ConcurrentHashMap** Lists and Employee objects of Iterating from his used code and not with Metrics. – ravi Jun 06 '16 at 11:53
  • @ravi In that case, he should post a question about `ConcurrentHashMap`. I've used arrays for the sake of simplicity so that every developer can understand the principle and adapt it to whichever constructs he or she wants to use. – Bruno Lowagie Jun 06 '16 at 13:47
  • I see that someone down-voted my answer. That's reason enough to stop spending any time on this question. I predict that it won't get any better answer because the question is really bad. Only if @kks does an effort to explain the question in a better way, there's a chance that someone can help, but so far, I don't see any effort or any attempt to make the question answerable. – Bruno Lowagie Jun 06 '16 at 14:06
  • 1
    "If you do not award your bounty within 7 days (plus the grace period), the highest voted answer created after the bounty started with a minimum score of 2 will be awarded half the bounty amount." - Bruno only needs 2 more votes to get 25 points in a couple of days, and the OP cannot do anything about it. – Amedee Van Gasse Jun 07 '16 at 11:17
1

Basically @Bruno Lowagie said everything that is required.

The thing is, you know exactly what columns you want to print, so just do it like this, so you don't need to convert your map into a two dimensional array:

private static PdfPTable rawDataTable() throws DocumentException {
...
    // outer loop for your rows
    for (int i = 0 ; i < emp_HistoryList.size() ; i++) {
        for (int j = 0 ; j < emp_HistoryList.values() ; j++) {
            EmpHistory item = emp_HistoryList.get(j);
            Cell cell;
            switch (j) {
                // I don't know your data types, so you might not need to convert.
                case 0: cell = new PdfPCell(
                            new Phrase(String.valueOf(item.getId()));
                        break;
                case 1: cell = new PdfPCell(
                            new Phrase(String.valueOf(item.getName()));
                        break;
                // ... create cell with all the data you require of the 33 columns
                default: cell = new PdfPCell(
                            new Phrase(""));
            }
            table.addCell(cell)       
        }
    }