亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 PdfPTable 列(iText)獲取絕對寬度

從 PdfPTable 列(iText)獲取絕對寬度

一只斗牛犬 2022-07-20 12:16:20
當用相對大小指定表列時,如何從iText獲取列的絕對寬度?我試過的我指定了 3 列,它們的相對寬度為 float,如下所示:PdfPCell cell2;PdfPTable table2 =  new PdfPTable(new float[]{(float) 4.5, (float) 0.5, 9});table2.setWidthPercentage(100);我得到了什么我嘗試使用table2.getAbsoluteWidths()[2]但結果是 float 0.0。我所期望的在 PDF 上動態計算表格寬度之后,我想獲得每一列的絕對寬度(最大化)。
查看完整描述

1 回答

?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

問題及說明

該函數table.getAbsoluteWidths()依賴于必須設置表的totalWidthtable.getTotalWidth() > 0的要求,因此.

這是因為在com.itextpdf.text.pdf.PdfPTable類內部調用了一個方法calculateWidths(),然后計算所有列的絕對寬度:

this.absoluteWidths[k] = this.totalWidth * this.relativeWidths[k] / total;

解決方案

為了確保在檢索relativeWidths數組之前設置totalWidth,您需要:

  • (A)設置totalWidth this answer中所述

  • (B) 將單元格添加到表格并將表格添加到文檔

解決方案代碼

以下代碼結合了您的算法,以根據列的最大寬度限制跨單元格拆分文本(即長地址或alamat):

import com.itextpdf.text.*;

import com.itextpdf.text.pdf.*;


import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Arrays;


public class TableWidthSample {


    public static void main(String[] args) {

        Document document = new Document();

        try {

            PdfWriter.getInstance(document, new FileOutputStream("TableColumnWidth.pdf"));

            document.open();


            PdfPTable table = createTableWithRelativeColumnWidths();


            // needed for calculation of getAbsoluteWidths: (A) totalWidth is set for table

            table.setTotalWidth(calculateTableWidthBasedOnPageA4(document, table));

            // now it prints width, because (A)

            printTableWidth(table, "after totalWidth set manually"); // absoluteWidths: [134.4857, 14.942857, 268.9714]


            // long text, that needs to be split among cells (fullAlamatPP)

            String text = "this is a very long text. The text contains a full address. Because the text is too long to be shown in the last cell, it is split.";

            // your CODE to fill text into cells based on restrictions

            addTextAcrossTableCells(table, text);


            document.add(table);


/*

            // need to add filled table to doc (B)

            addToDocumentCellsAndTable(document, table);

            // now it prints width, because (B)

            printTableWidth(table, "after added to doc"); // absoluteWidths: [134.4857, 14.942857, 268.9714]

*/

            document.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (DocumentException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }


    private static PdfPTable createTableWithRelativeColumnWidths() {

        float[] relativeWidths = {4.5F, 0.5F, 9F};

        PdfPTable table = new PdfPTable(relativeWidths);

        table.setWidthPercentage(100F);

        printTableWidth(table, "after table created"); // absoluteWidths: [0.0, 0.0, 0.0]

        return table;

    }


    private static float calculateTableWidthBasedOnPageA4(Document document, PdfPTable table) {

        return (PageSize.A4.getWidth() - document.leftMargin() - document.rightMargin())

                * table.getWidthPercentage() / 100;

    }


    private static void addToDocumentCellsAndTable(Document document, PdfPTable table) throws DocumentException {

        // needed for calculation of getAbsoluteWidths: (B.1) add cells to table

        table.addCell("Hello");

        table.addCell("World");

        table.addCell("!");

        printTableWidth(table, "after cells added to table"); // absoluteWidths: [0.0, 0.0, 0.0]


        // needed for calculation of getAbsoluteWidths: (B.2) add table to doc

        document.add(table);

    }


    private static void addTextAcrossTableCells(PdfPTable table, String text) throws IOException, DocumentException {

        // restrictions; this is width of a column from table

        float maxColumnWidth = table.getAbsoluteWidths()[2]; // 330.12103F;

        System.out.println("use width of third column as max: " + maxColumnWidth);

        // sample font used for calculation of text-width

        Font font = new Font(BaseFont.createFont("Courier", BaseFont.CP1250, true), 12);


        // alamatSesuaiKtpPP

        String splitText[] = getTextPartsUsingFontWithMaxWidth(text, font, maxColumnWidth);

        String dottedLine = "..";

        table.addCell("Alamat / Address:");


        // p_alamat1_ct

        Phrase phrase1 = new Phrase(splitText[0], font);

        phrase1.add(dottedLine);

        PdfPCell cell1 = new PdfPCell(phrase1);

        cell1.setBackgroundColor(BaseColor.LIGHT_GRAY);

        cell1.setBorder(PdfPCell.NO_BORDER);

        table.addCell(cell1);


        // p_alamat2_ct

        Phrase phrase2 = new Phrase(splitText[1], font);

        phrase2.add(dottedLine);

        PdfPCell cell2 = new PdfPCell(phrase2);

        cell2.setBorder(PdfPCell.NO_BORDER);

        table.addCell(cell2);

    }


    private static String[] getTextPartsUsingFontWithMaxWidth(String text, Font font, float maxWidth) {

        String results[] = new String[] {"",""};

        String firstPartOfText = " ";

        float widthOfText = 0;

        for (int i = 0; i < text.length();i++) {

            firstPartOfText += text.charAt(i);

            widthOfText = font.getCalculatedBaseFont(true).getWidthPoint(firstPartOfText, font.getCalculatedSize());

            System.out.printf("%d: widthOfText: %f\n", i, widthOfText);

            if (widthOfText > maxWidth) {

                results[0] = firstPartOfText.substring(0, firstPartOfText.length() - 1);

                results[1] = text.substring(i); // second argument "text.length()" is not needed

                break;

            }

        }


        if (results[0] == "") {

            results[0] = text;

        }

        return results;

    }


    private static void printTableWidth(PdfPTable table, String labelText) {

        float[] absoluteWidths = table.getAbsoluteWidths();

        System.out.println(labelText + "> getAbsoluteWidths: " + Arrays.toString(absoluteWidths));

    }

}


查看完整回答
反對 回復 2022-07-20
  • 1 回答
  • 0 關注
  • 572 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號