【问题标题】:Fill the dynamic data with each row columns by column Using iText in Java在Java中使用iText逐列填充动态数据
【发布时间】:2016-09-28 07:35:45
【问题描述】:
  • 大家好
  • 我有一个使用 iText 生成的 pdf 报告,其中包含一个添加到 MultiColumnText 的 PdfPTable,有时它会变得如此之大,以至于它会被拆分到多个页面上,
  • 这里添加了示例代码,其工作方式为

第-1页

----------------------------------- -------------------------------------------------- -------------------------------------------------+ |第一 - Emp1-NO |第二 - Emp1-名称|第三 - Emp1-设计 |

| 4th - Emp2-NO | 5th - Emp2-名称|第 6 名 - Emp2-设计 |

| 7th - Emp3-NO | 8th - Emp3-名称| 9th - Emp3-设计 |

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

  • 但我想先填充数据 没有所有行,然后是每一列,即逐列

  • 如下所示

第-1页

----------------------------------- -------------------------------------------------- -------------------------------------------------+ |第一 - Emp1-NO | 4th - Emp1-名称| 7th - Emp1-设计 |

| 2nd - Emp2-NO | 5th - Emp2-名称| 8th - Emp2-设计 |

| 3rd - Emp3-NO | 6th - Emp3-名称| 9th - Emp3-设计 |

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

**我的代码是**

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;
    }
}

**示例 PDF 是 **

问题更新

  1. 我有 150 名员工数据

  2. 每个员工都有姓名、上班时间和下班时间

  3. 请找到 PDF 图片

  4. 我需要有关单元格填充逻辑的帮助 一种。在第一列打印员工 ID - 150 名员工 湾。然后已经用员工姓名打印了每一行第二列 C。然后用 In time 3rd Column 打印

仅来自- 首先打印 3 行第一列 [1066,1067,1069] Ids 然后再次打印退出 3 行第二列 [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
}

问题更新 - 2

  • 我正在使用 Java 和 iText
  • 我需要将文本分列,
  • 我创建 PDFTable 为:PdfPTable table = new PdfPTable(33);
  • 问题是PdfPTable逐行填充表格,即你先给第1行第1列的单元格,再给第1行第2列的单元格,以此类推,但我需要逐列,因为这就是将数据提供给我的方式。

我需要喜欢:

1 3 5 2 4 6

  • 当前代码作为

1 2 3 4 5 6

  • 请问我在示例代码中做了哪些更改
  • 请对此提供帮助,在此先感谢。

【问题讨论】:

  • [1] 您使用的是 iText 5 (com.itextpdf),但您提到了 MultiColumnTextMultiColumnText 在 iText 5 中不存在,无论如何我都无法在您的长代码 sn-p 中找到它。 [2] 屏幕截图是关于什么的?看起来不错,但我不明白它与您的问题有何关系。那是期望的输出吗?如果不是,它有什么问题? (它太小而难以辨认。)您的代码太长,任何人都无法阅读。请用简单的话重新表述你的问题。现在你只是让人们感到困惑。
  • 感谢@BrunoLowagie,只是 [1] 我有 EmpInfo 列表,它有 105 个对象,正在迭代 105 个 EmpInfo 对象,每个 Emp 有 3 个 HistoryRecordsData。 ConcurrentHashMap&lt;String,EmpHistory&gt; emp_HistoryList = new ConcurrentHashMap&lt;String, EmpHistory&gt;(); 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 }
  • 请在评论部分更新您的复制/粘贴代码的问题。另外:目前尚不清楚您要做什么。请像在与不了解您要求的人交谈一样进行解释。
  • 感谢@BrunoLowagie,抱歉让您感到困惑,我已经更新了我的要求,
  • 你确实很混乱。您提出的问题好像是 iText 问题,但实际上,这是一个与 iText 没有真正关系的简单编程问题。我将创建一个答案,解释解决您的问题所需的基本数学。请考虑参加数学课。

标签: java arrays itext java.util.concurrent itextpdf


【解决方案1】:

基本上@Bruno Lowagie 说了所有需要的内容。

问题是,您确切地知道要打印哪些列,所以就这样做,这样您就不需要将地图转换为二维数组:

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)       
        }
    }

【讨论】:

    【解决方案2】:

    出于逻辑原因,表格在 iText 中逐行填充:

    如果你想改变顺序,你需要先创建一个数据矩阵来自己做。一种方法是创建一个二维数组(还有其他方法,但为了简单起见,我使用数组)。

    RowColumnOrder 示例显示了它是如何完成的。

    这是正常行为:

    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);
    

    你想改变这种行为,这意味着你必须创建一个矩阵来改变行和列的填充顺序:

    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;
        }
    }
    

    如您所见,不涉及 iText 代码。我有 15 个单元格要添加到一个 5 列和 3 行的表中。为了实现这一点,我创建了一个String[3][5] 数组,我将填充一列的每一行,然后在当前列已满时切换到下一列。一旦我有了二维矩阵,我就可以用它来填充PdfPTable

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

    如您所见,row_column_order.pdf 中的第二个表为您提供了您想要的结果。

    【讨论】:

    • @kks 我看到你在我回答这个问题后打开了赏金。我的回答你不明白什么?什么不清楚?我发布了您遇到的情况和您想要的情况的屏幕截图。该屏幕截图取自使用代码示例创建的 PDF,该示例解释了如何获得所需的结果。你还需要什么?您声称“当前的答案没有包含足够的细节。”简直不可思议。我的回答非常详细!
    • @Bruno Lowagie:很好的解释,我认为 @KKS 希望代码使用 ConcurrentHashMap 列表和 Employee 对象从他使用的代码中迭代,而不是使用指标。
    • @ravi 在这种情况下,他应该发布一个关于ConcurrentHashMap 的问题。为了简单起见,我使用了数组,以便每个开发人员都能理解其原理并使其适应他或她想要使用的任何构造。
    • 我看到有人否决了我的回答。这足以让我们停止在这个问题上花费任何时间。我预测它不会得到更好的答案,因为这个问题真的很糟糕。只有@kks 努力以更好的方式解释这个问题,才有可能有人可以提供帮助,但到目前为止,我没有看到任何努力或尝试让这个问题得到解答。
    • “如果您在 7 天内(加上宽限期)未授予您的赏金,则在赏金开始后创建的最低得分为 2 的最高投票答案将获得一半的赏金。” - 布鲁诺只需要多投 2 票就可以在几天内获得 25 分,而 OP 对此无能为力。
    猜你喜欢
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多