ItextPdf Width Does Not Expand for Landscape Page

2019-08-23 13:31发布

I am trying to put a table on a PDF page that has been rotated for landscape in my 'PdfPageEventHelper':

public void onStartPage(PdfWriter writer_,Document document_) {
        writer_.addPageDictEntry(PdfName.ROTATE,PdfPage.LANDSCAPE);
    }

That part seems to be working but when I create my table with 10 columns, setting the width does not seem to work:

float sizeY=page.getWidth();
PdfPTable table=new PdfPTable(10);
table.setTotalWidth(sizeY);
float[] widths=new float[] {1.f,1.5f,4.f,1.f,1.f,1.f,1.f,1.f,1.f,1.f};
table.setWidths(widths);

The table width always seems to be the default (80% of the portrait page width). How do I get the table to use the landscape page width? TIA.

1条回答
太酷不给撩
2楼-- · 2019-08-23 13:39

You are using the old iText 5. There are plenty of quirks in iText 5 that are solved in iText 7.

In iText 7, we have the concept of the UnitValue which helps iText determine whether something is an absolute value (in user units / points) or a relative value (a percentage).

In iText 5, this concept is unknown. The PdfPTable class has two parameters for the width of a table:

  • The width as a percentage: 80% by default,
  • The absolute width

By default, the width as a percentage is used. If you want to use the absolute width, you need to "pull the switch" with the setLockedWidth() method:

table.setTotalWidth(sizeY);
table.setLockedWidth(true);

I know this is odd, but then again, you are using the old iText version. If you want a more consistent API, please use iText 7. That upgrade is really significant. We've spent an awful amount of time and money on improving iText, so it's kind of frustrating to see that new iText developers choose to work with iText 5 rather than with iText 7.

查看更多
登录 后发表回答