How to fit the text in a cell itext 7

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

FYI

How to get the content as above, by using Cell with itext 7 library

I used the cell.setPadding(0f); but it didn't helped me to get the results as expected.

回答1:

It seems that you forgot to set the leading of the content you are adding to the Cell. I tried to mimic the screen shot you shared:

This is the code I used to do so:

public void createPdf(String dest) throws IOException {     // step 1     PdfDocument pdfDocument = new PdfDocument(new PdfWriter(dest));     pdfDocument.setDefaultPageSize(PageSize.A4.rotate());     // step 2     Document document = new Document(pdfDocument);     // step 3     Table table = new Table(new float[]{ 50 , 50 });     table.setWidthPercent(30);     table.addCell(new Cell().setPadding(0).setTextAlignment(TextAlignment.CENTER)             .add(new Paragraph("4.0").setMultipliedLeading(1.2f).setItalic()));     table.addCell(new Cell().setPadding(0).setTextAlignment(TextAlignment.CENTER)             .add(new Paragraph("0.14").setMultipliedLeading(1.2f).setItalic()));     document.add(table);     // step 4     document.close(); }

In this case, I used a multiplied leading of 1.2f. Feel free to change that value.

Note: it is very annoying that you can't set the value of the level on a parent (e.g. the table, the document,...). I have created a feature request on JIRA in the hope that this will be supported in the next version.



回答2:

Although there is not an appropriate setter for default leading, there is a way to set it on document / table / other class that implements IPropertyContainer. Just use setProperty method. Since LEADING and ITALIC_SIMULATION properties are inherited, the container and all its children will have this property (unless it's overwritten).

I've rewritten Bruno's code, and the next snippet performs results you want to have.

    PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName));     pdfDocument.setDefaultPageSize(PageSize.A4.rotate());      Document document = new Document(pdfDocument);      Table table = new Table(new float[]{ 50 , 50 });     table.setWidthPercent(30);     document.setProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, 1.2f));     document.setProperty(Property.ITALIC_SIMULATION, true);      table.addCell(new Cell().setPadding(0).setTextAlignment(TextAlignment.CENTER)             .add("4.0"));     table.addCell(new Cell().setPadding(0).setTextAlignment(TextAlignment.CENTER)             .add("0.14"));     document.add(table);     document.close();

However it's strongly recommended not to set properties by yourself unless you understand what results it will cause.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!