简体   繁体   中英

Itext 5 Table rows splitting to new page and repeating

I am using itext 5 legacy for the first time and I am new to app development. I am generating a table that keeps splitting the columns into new rows on a new page and it would repeat the data.

The first Table: 第一个表 The second table with split columns and repeating data: 带有拆分列和重复数据的第二个表

Third table: 第三张表

The fourth table: 第四张表

The fifth Table: 第五表

The table is required to be one long row. Please help me rectify this,

Here is the code:

    private void createPdf() throws FileNotFoundException, DocumentException,IOException {
       // getIntent().setType("application/pdf");
        Toast.makeText(this,"GENERATING PDF ..."+ directory_path,Toast.LENGTH_LONG).show();
        File file = new File(directory_path+filename);
        if (!file.exists())
        {
            file.mkdirs();
        }
        ProductCondition prodCond = new ProductCondition(true,"GREEN","BFobrourinbiurfufbjfnbbu");
        ProductOperations prodOper = new ProductOperations(true,true,true,1000,986,500,"OBNobdfiuvdob");
        Product product = new Product("bkbukb","sfdvsf","sdfsdfs","1sfdssV45",prodCond,prodOper);
        technicians.addProduct(product);
        Document document = new Document(PageSize.A1.rotate());
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(directory_path+filename));
        document.open();
        PdfPTable table = new PdfPTable(15);
        table.setTotalWidth(5000);
        table.setWidthPercentage(100);
        List<String> listData =new ArrayList<>() ;
        listData = GetTechnicianData(technicians);
        Image image1 = GetImage();
        Image image2 = GetImage();
        table.addCell("Bloop");
        table.addCell("han Solo");
        table.addCell("Hamburger");
        table.addCell("NUmber time");
        table.addCell("boogaloo");
        table.addCell("Boo thang");
        table.addCell("Spanish");
        table.addCell("Inquisition");
        table.addCell("Never ");
        table.addCell("Death");
        table.addCell("Test ");
       // table.addCell("Button");
        table.addCell("Lights");
        table.addCell("Sunshine");
        table.addCell("Comment");
        table.addCell("Images");
        table.setHeaderRows(3);
        table.setFooterRows(1);
        table.getDefaultCell().setBackgroundColor(GrayColor.GRAYWHITE);
        PdfPCell cell;
        Toast.makeText(this,"ADDING PRELIMINARY DATA",Toast.LENGTH_LONG).show();
            for (int c = 0; c < 14; c++) {
                cell = new PdfPCell();
                cell.setFixedHeight(50);
                cell.addElement(new Paragraph(listData.get(c)));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                //cell.setBorder(PdfPCell.NO_BORDER);
                table.addCell(cell);
                table.setKeepTogether(true);
            }
        Paragraph p = new Paragraph();
        p.add(new Chunk(image1,0,0,true));
        p.add(new Chunk(image2,0,0,true));
        cell = new PdfPCell();
        cell.addElement(p);
        //cell.setBorder(PdfPCell.NO_BORDER);
        table.addCell(cell);
        //document.add(table);
        Toast.makeText(this,"ADDING IMAGES...",Toast.LENGTH_LONG).show();

          /*  cell = new PdfPCell();
            Paragraph p = new Paragraph();
            p.add(new Chunk(image1,0,0,true));
            p.add(new Chunk(image1,0,0,true));
            cell.addElement(p);
            table.addCell(cell);*/

       // document.add(table);


        PdfContentByte canvas = writer.getDirectContent();
        PdfTemplate tableTemplate = canvas.createTemplate(5000, 2600);
        table.writeSelectedRows(0, -1, 0, 800, tableTemplate);
        PdfTemplate clip;
        for (int j = 0; j <5000; j += 1000) {
            table.setKeepTogether(true);
            document.newPage();
            for (int i = 2600; i > 0; i -= 1300) {

                clip = canvas.createTemplate(2000, 1300);
                clip.addTemplate(tableTemplate, -j, 1750 - i);
                canvas.addTemplate(clip, 50, 312);
                table.setKeepTogether(true);
                //canvas.addImage(image1);
            }
        }
        // byte [] pdf = Files.readAllBytes(file.toPath());
        Uri filepdf = Uri.fromFile(new File(directory_path+filename));
        UploadTask uploadTask = storageReference.child(technicians.getEmailAddress()).child("PDFUpdate").putFile(filepdf);
        Toast.makeText(this,"PDF Generated Successfully",Toast.LENGTH_LONG).show();
        document.close();

       /* PackageManager packageManager = context.getPackageManager();
        Intent testIntent = new Intent(Intent.ACTION_VIEW);
        testIntent.setType("application/pdf");
        List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() > 0) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/pdf");
            context.startActivity(intent);
        } else {
            Toast.makeText(context, "Download a PDF Viewer to see the generated PDF", Toast.LENGTH_SHORT).show();
        }
*/
    }
    private void createPdfWrapper() throws FileNotFoundException, DocumentException ,IOException{

        int hasWriteStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    showMessageOKCancel("You need to allow access to Storage",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        ActivityCompat.requestPermissions(CentralHome.this, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                REQUEST_CODE_ASK_PERMISSIONS);
                                    }
                                }
                            });
                    return;
                }
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_ASK_PERMISSIONS);
                return;
            }

        } else {
            createPdf();
        }
    }

    private Image GetImage() throws BadElementException,IOException{


            Drawable d = getResources().getDrawable(R.drawable.logo);
            BitmapDrawable bitDw = ((BitmapDrawable) d);
            Bitmap bmp = bitDw.getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            Image image = Image.getInstance(stream.toByteArray());
            image.scalePercent(10);
            return image;
            // document.add(image);

    }

}

In createPdf you have a loop that adds sections of the template with the whole table to separate pages:

for (int j = 0; j <5000; j += 1000) {
    table.setKeepTogether(true);
    document.newPage();
    for (int i = 2600; i > 0; i -= 1300) {
        clip = canvas.createTemplate(2000, 1300);
        clip.addTemplate(tableTemplate, -j, 1750 - i);
        canvas.addTemplate(clip, 50, 312);
        table.setKeepTogether(true);
        //canvas.addImage(image1);
    }
}

Each section is 2000 units wide ( canvas.createTemplate(2000, 1300) ) but when advancing to the next section you only go right by 1000 units ( j += 1000 ). Thus, each new section (except the first one) repeats the last three columns (the second half) of the previous section.

You can prevent these repetitions by going right by 2000 units after each section, ie by replacing

for (int j = 0; j <5000; j += 1000)

by

for (int j = 0; j <5000; j += 2000)

As an aside, there are numerous other weirdnesses in your code, eg

table.setHeaderRows(3);
table.setFooterRows(1);

(here you declare that you have three header rows and one footer row to repeat automatically if the table is added to the Document directly and split over multiple pages; as you don't add the table to the Document but manually to a template, that functionality is not used which is fortunate as you only create enough cells to fill two rows, not even enough for the declared header rows)

and multiple calls of

table.setKeepTogether(true)

after already having rendered the table in

table.writeSelectedRows(0, -1, 0, 800, tableTemplate)

After rendering the table it is too late to set properties controlling the rendering process...


In a comment you said that you only wanted to have a normal 15 column table, not one whose columns are spread across multiple pages. In that case why don't you simply do

Document document = new Document(PageSize.A1.rotate());
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(directory_path+filename));
document.open();
PdfPTable table = new PdfPTable(15);
table.setWidthPercentage(100);

... create cells and add them to the table ...

document.add(table);
document.close();

All the usage of PdfContentByte , PdfTemplate , and writeSelectedRows is completely unnecessary for your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM