I made an export pdf system using the java Itext pdf library, but there is a problem when I want to split the data of each page, I want to dynamically divide the data of each page using input, how to do it?like the code below, but the result is not as expected
//looping data row
PdfPTable itemTable = new PdfPTable(headerColumns.length);
itemTable.setWidthPercentage(100);
for(int i = 0;i< data.size();i++){
// header area
PdfPCell area = new PdfPCell(new Phrase(data.get(i).get("area").toString()));
area.setPaddingLeft(4);
area.setVerticalAlignment(Element.ALIGN_MIDDLE);
area.setHorizontalAlignment(Element.ALIGN_CENTER);
itemTable.addCell(area);
// header new_sa
PdfPCell newSa = new PdfPCell(new Phrase(data.get(i).get("new_sa").toString()));
newSa.setPaddingLeft(4);
newSa.setVerticalAlignment(Element.ALIGN_MIDDLE);
newSa.setHorizontalAlignment(Element.ALIGN_CENTER);
itemTable.addCell(newSa);
// header new_sa
PdfPCell saMtd = new PdfPCell(new Phrase(data.get(i).get("sa_mtd").toString()));
saMtd.setPaddingLeft(4);
saMtd.setVerticalAlignment(Element.ALIGN_MIDDLE);
saMtd.setHorizontalAlignment(Element.ALIGN_CENTER);
itemTable.addCell(saMtd);
// header sa_last_month
PdfPCell saLastMonth = new PdfPCell(new Phrase(data.get(i).get("sa_last_month").toString()));
saLastMonth.setPaddingLeft(4);
saLastMonth.setVerticalAlignment(Element.ALIGN_MIDDLE);
saLastMonth.setHorizontalAlignment(Element.ALIGN_CENTER);
itemTable.addCell(saMtd);
//set maxmimum data per page 2
if(itemTable.getRows().size() == 2){
document.newPage();
}
document.add(table);
document.add(itemTable);
}
document.close();
pdf result of the code above
picture page 1
picture page 2
In a comment you clarified
the results that I expect, such as data per page for example 2 , in the results of the image I include it is like a bug where the data on the initial page is 1 but the data is repeated on the 2nd page
If you don't want the data to repeat, then you should not add the same itemTable object again and again but instead create a new one at the start of the loop.
I.e. you should pull the two lines into the loop that currently are before the loop, instead of
PdfPTable itemTable = new PdfPTable(headerColumns.length);
itemTable.setWidthPercentage(100);
for(int i = 0;i< data.size();i++){
...
document.add(itemTable);
}
use
for(int i = 0;i< data.size();i++){
PdfPTable itemTable = new PdfPTable(headerColumns.length);
itemTable.setWidthPercentage(100);
...
document.add(itemTable);
}
Related
I am writing a Java code to generate a PDF template. In the pdf's header section, I have created a pdfTable which has 7 cells including an image cell (Logo), a text field (Id Number) and remaining 5 cells to populate the actual Id Number.
In the output, I should get a bigger image cell (representing the Logo) and Id number cells must be smaller in size than the image cell. Example, as in the below image (Expected Result).
However when the template is generated, I am unable populate as expected as shown in the above image (Expected Result).
When the PDF is generated, all the cells are taking the size of the image cell.
I have tried with different approaches like setting column widhts, setFixedHeight(), setRowSpan(), setColumnSpan() methods etc. But nothing worked. Below image shows my output (Current Output).
Below is code which I have written.
public class NbaBafTemplateGenerator {
private void createNbaBafTemplate(File outPutfileName, NbaBafTemplateData formData,String logoName) {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outPutfileName));
document.open();
PdfPTable table = null;
// Passing the data as a single String
//IdNumber varible is of type String and has 5 characters of the number.
table = NbaBafTemplatePage.createHeaderTable(logoName + ",Id Number: , " +
formData.getIdNumber(), 7, "", "","1.5f, 1f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f");
document.add(table);
}// END OF CLASS NbaBafTemplateGenerator.
//Class NbaBafTemplatePage Begins.
public class NbaBafTemplatePage extends PdfPageEventHelper {
public static PdfPTable createHeaderTable(String text, int columnCount, String colour, String align, String colSize)
throws DocumentException, IOException {
PdfPTable table = null;
table = new PdfPTable(columnCount); // 7 columns.
table.setWidthPercentage(100); // Width 100%
table.setSpacingBefore(0f); /
table.setSpacingAfter(10f);
//Assigning column widths based on input width params.
float[] tablecolumnWidths = {
Float.parseFloat(colSize.split(",")[0]),
Float.parseFloat(colSize.split(",")[1]),
Float.parseFloat(colSize.split(",")[2]),
Float.parseFloat(colSize.split(",")[3]),
Float.parseFloat(colSize.split(",")[4]),
Float.parseFloat(colSize.split(",")[5]),
Float.parseFloat(colSize.split(",")[6])};
PdfPCell imgCell = new PdfPCell(createImageCell(text.split(",")[0]));
//imgCell.setColspan(3);
//imgCell.setRowspan(3);
imgCell.setBorder(PdfPCell.NO_BORDER);
imgCell.setHorizontalAlignment(Element.ALIGN_LEFT);
imgCell.setVerticalAlignment(Element.ALIGN_LEFT);
table.addCell(imgCell);
PdfPCell idCell = new PdfPCell(new Paragraph(text.split(",")[1]));
idCell.setBorderColor(BaseColor.BLACK);
idCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
idCell.setPaddingLeft(10);
idCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
idCell.setVerticalAlignment(Element.ALIGN_RIGHT);
table.addCell(idCell);
PdfPCell cellC0 = new PdfPCell(new Paragraph(text.split(",")[2]));
cellC0.setBorderColor(BaseColor.BLACK);
cellC0.setHorizontalAlignment(Element.ALIGN_CENTER);
cellC0.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cellC0);
PdfPCell cellC1 = new PdfPCell(new Paragraph(text.split(",")[3]));
cellC1.setBorderColor(BaseColor.BLACK);
cellC1.setHorizontalAlignment(Element.ALIGN_CENTER);
cellC1.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cellC1);
PdfPCell cellC2 = new PdfPCell(new Paragraph(text.split(",")[4]));
cellC2.setBorderColor(BaseColor.BLACK);
cellC2.setHorizontalAlignment(Element.ALIGN_CENTER);
cellC2.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cellC2);
PdfPCell cellC3 = new PdfPCell(new Paragraph(text.split(",")[5]));
cellC3.setBorderColor(BaseColor.BLACK);
cellC3.setHorizontalAlignment(Element.ALIGN_CENTER);
cellC3.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cellC3);
PdfPCell cellC4 = new PdfPCell(new Paragraph(text.split(",")[6]));
cellC4.setBorderColor(BaseColor.BLACK);
cellC4.setHorizontalAlignment(Element.ALIGN_CENTER);
cellC4.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cellC4);
return table;
}//END OF METHOD createHeaderTable.
public static PdfPCell createImageCell(String path) throws DocumentException, IOException {
Image img = Image.getInstance(path);
PdfPCell cell = new PdfPCell(img, true);
return cell;
}
}
I am using Java and iText 5.x version.
Can anyone please let me know how to generate the pdf table with different cell sizes.
You can create a table with 2 rows (13 cells). Set the column-span of image cell equal to 2. Keep the remaining cells of the first row as blank, set their borders as 0 (invisible), and adjust their heights (cells of the first row) as per your required alignment.
Then add the remaining 6 cells to the table as a second row. Adjust column widths as per your requirement. Hope this helps.
PdfPTable table = new PdfPTable(7);
table.setWidthPercentage(100);
PdfPCell imageCell = new PdfPCell(image);
imageCell.setBorder(0);
imageCell.setRowspan(2);
table.addCell(imageCell);
for(int i=0; i<6;i++) {
PdfPCell blankCell = new PdfPCell();
blankCell.setBorder(0);
blankCell.setFixedHeight(20f);
table.addCell(blankCell);
}
PdfPCell cell22 = new PdfPCell(new Phrase("ID Number"));
table.addCell(cell22);
PdfPCell cell23 = new PdfPCell(new Phrase("9"));
table.addCell(cell23);
PdfPCell cell24 = new PdfPCell(new Phrase("6"));
table.addCell(cell24);
PdfPCell cell25 = new PdfPCell(new Phrase("0"));
table.addCell(cell25);
PdfPCell cell26 = new PdfPCell(new Phrase("5"));
table.addCell(cell26);
PdfPCell cell27 = new PdfPCell(new Phrase("1"));
table.addCell(cell27);
document.add(table);
I have a list of 100 records and i want to make a table in pdf with 3 columns. My problem is once the pdf file has been made it's 33 rows with 3 columns so it's 99 records not 100. How can i show the other one record in pdf table?
here is my code:
Document document = new Document(PageSize.A4, -60f, -60f, 18f, 5f);
PdfPTable table = new PdfPTable(3);
PdfPCell cell;
if (filterPins.size() > 0) {
for (int i = 0; i < filterPins.size(); i++) {
Bitmap bmp = getRecyclerViewScreenshot(pinList, i);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
cell = new PdfPCell(image, true);
cell.setPadding(0f);
cell.setBorder(Rectangle.NO_BORDER);
table.addCell(cell);
}
File myDirectory = new File(rootView.getContext().getFilesDir(), String.valueOf(factorNo));
if (!myDirectory.exists()) {
myDirectory.mkdirs();
}
File pdfFile = new File(myDirectory, fileName);
PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
document.open();
document.add(table);
document.close();
}
filterPins is my arrayList containing 100 records.
How can i show the other one record in pdf table?
First of all that also is a question you have to ask yourself. Do you want the 100th entry fill only a single of the three cells of a row? If yes, which one? Or should it span the whole row? Or would you prefer yet another construct?
Let's assume, though, you simply want the 100th entry to be the first cell in the 34th row and you also want the other cells in that row to be empty. In that case there is a PdfPTable utility method that fills the current row with empty cells (copies of the default cell):
table.completeRow();
if(yourlist.size() % 3 == 0){
int totalRows = yourlist.size() / 3;
create your pdf.
for example list.size() = 99 then you create 33 rows each row have 3 column.
}
else
{
int totalRows = yourlist.size() / 3;
for example if yourlist.size() = 100.
then first create 33 row each row have 3 column.
remaining 1 item add in new list after created 33 rows.
remaining 1 or 2 column add in new row.
Note : in any case you have remaining only 1 or 2.
}
How do I split the rows of the inner table. Problem description according to the image.
Here, I have table named PARENT_TABLE that has cell that contains two tables named HEADER_TABLE and CONTENT_TABLE
CONTENT_TABLE has a cell that contains INNER_TABLE. INNER_TABLE contains the dynamic rows/content whose height will be changed according to content.
So, If I make this table using one page it's working perfectly. But incase if I need to split the table in different pages it shows the error like image_2. Please help me out. As a result: The table should look like in the image_1 even if the page split into two or more pages.
Please checkout mentioned image to be more clear.
image_1
Attempt to read from field 'float com.itextpdf.text.pdf.ColumnText.maxY' on a null object reference
image_2
I just found out the solution. The issue occurs only in the case when trying to split the PDFPTable into two pages. I had used tableCell.setRowspan(2), so when trying to split the table above issue occurs.
SOLVED IT: I just made an empty cell in place of using tableCell.setRowspan(2).
private PdfPTable contentWithDateTitleAndDescription(String stringData1, String stringData2, String stringData3, String stringData4) throws IOException, BadElementException {
float relativeWidth[] = {2, 7};
PdfPTable table = new PdfPTable(relativeWidth);
table.setWidthPercentage(100);
PdfPCell cellA = new PdfPCell();
cellA.setBorder(Rectangle.NO_BORDER);
// dateCell.setRowspan(2);
cellA.setPaddingLeft(15);
cellA.setVerticalAlignment(Element.ALIGN_CENTER);
cellA.setPaddingTop(7);
Paragraph dateParagraph = new Paragraph(stringData1);
cellA.addElement(dateParagraph);
PdfPCell emptyCellB = new PdfPCell();
emptyCellB.setBorder(Rectangle.NO_BORDER);
PdfPCell cellC = new PdfPCell();
cellC.setBorder(Rectangle.NO_BORDER);
cellC.setVerticalAlignment(Element.ALIGN_LEFT);
Paragraph titleParagraph = new Paragraph(stringData2 + " / " + stringData3);
cellC.addElement(titleParagraph);
PdfPCell cellD = new PdfPCell();
cellD.setBorder(Rectangle.NO_BORDER);
cellD.setVerticalAlignment(Element.ALIGN_LEFT);
Paragraph descriptionParagraph = new Paragraph(stringData4);
cellD.addElement(descriptionParagraph);
cellD.setPaddingBottom(15);
table.addCell(cellA);
table.addCell(cellC);
table.addCell(emptyCellB);
table.addCell(cellD);
return table;
}
I have a table (2 x 2).
If I add a Phrase as cell in the first cell with rowspan 2, it works. But if I use an Image as cell, rowspan never apply.
float[] rowwidths2 = {0.6f,0.4f};
PdfPTable felsoegyharmad = new PdfPTable(rowwidths2);
felsoegyharmad.setWidthPercentage(100);
PdfPCell kepcell = new PdfPCell(new Phrase("image place", fontAlap));
kepcell.setRowspan(2);
felsoegyharmad.addCell(kepcell);
felsoegyharmad.addCell(new Phrase("1", fontAlap));
felsoegyharmad.addCell(new Phrase("2", fontAlap));
Code above is works as advertise.
But this code under is never rowspanned:
PdfPCell kepcell = new PdfPCell();
kepcell.addElement(Image.getInstance(path));
kepcell.setRowspan(2);
felsoegyharmad.addCell(kepcell);
felsoegyharmad.addCell(new Phrase("1", fontAlap));
felsoegyharmad.addCell(new Phrase("2", fontAlap));
How can I put this image into the first column but in height as two rows?
In case you wonder why nobody is answering your question. That's simple: the problem you describe can not be reproduced. I have taken your code snippet, and I have created the following standalone example:
PdfPTable table = new PdfPTable(2);
PdfPCell imageCell = new PdfPCell();
imageCell.addElement(Image.getInstance(IMG));
imageCell.setRowspan(2);
table.addCell(imageCell);
table.addCell(new Phrase("1"));
table.addCell(new Phrase("2"));
For the full source code, see ImageRowspan
The resulting PDF looks like this:
As you can see, the table has two columns and two rows. The first cell (the one with the image) spans two rows. You can download cmp_image_rowspan.pdf from out git repository.
This question already has answers here:
Right aligning text in PdfPCell
(6 answers)
Closed 7 years ago.
I have a table where in the first row there are only images and in the second row there are only descriptions of the images. I handle this by creating a table with the size (columns) of the amount of images and then filling the cells with tables with size 1 (2 rows = 1st row the image, 2nd row the description). After setting cell alignment of the 1st row to center, the second row will not apply the align and the description stays on the left ... is this a bug?
Integer size = filepathArray.length;
PdfPTable pdfPTable = new PdfPTable(size);
for (int i = 0; i < size; i++) {
PdfPTable inner = new PdfPTable(1);
try {
PdfPCell image = new PdfPCell();
PdfPCell description = new PdfPCell();
PdfPCell cell = new PdfPCell();
image.setImage(Image.getInstance(getImageAsByteArray(filepathArray[i])));
image.setFixedHeight(32);
image.setBorder(Rectangle.NO_BORDER);
image.setHorizontalAlignment(Element.ALIGN_CENTER);
inner.addCell(image);
description.addElement(new Chunk(filepathArray[i], FontFactory.getFont("Arial", 8)));
description.setBorder(Rectangle.NO_BORDER);
description.setHorizontalAlignment(Element.ALIGN_CENTER);
inner.addCell(description);
cell = new PdfPCell();
cell.addElement(inner); // needed to actually remove the border from the cell which contains the inner table because tables have no setter for the border
cell.setBorder(Rectangle.NO_BORDER);
pdfPTable.addCell(cell);
} catch (Exception e) {
}
}
pdfPTable.setHorizontalAlignment(Element.ALIGN_LEFT);
Result: the image is centered, the text is not, no way, I've tried everything! Also addElement() removes all previously set alignments (table and cell elements, is this a bug?) so I have to set the alignment AFTER I added the content to the cell or table.
This is wrong:
PdfPCell description = new PdfPCell();
description.addElement(new Chunk(filepathArray[i], FontFactory.getFont("Arial", 8)));
description.setHorizontalAlignment(Element.ALIGN_CENTER);
It is wrong because you are mixing text mode:
PdfPCell description = new PdfPCell(new Phrase(filepathArray[i], FontFactory.getFont("Arial", 8)));
description.setHorizontalAlignment(Element.ALIGN_CENTER);
With composite mode:
PdfPCell description = new PdfPCell();
Paragraph p = new Paragraph(filepathArray[i], FontFactory.getFont("Arial", 8));
p.setAlignment(Element.ALIGN_CENTER);
description.addElement(p);
Seems like you have tried everything but using the approaches that are explained in the documentation ;-)