I'm generating a PDF document with iTextSharp. This document must have only one page. In other words the content must fit the page size. Is it possible to achieve this with iTextSharp?
I tried to get the height of the content before adding it to the document, so I can calculate the total size before creating the document, but some content types (tables for example) don't have height until they are added to the document.
To receive the height of the table in iText7 you should work with
IRenderer. We can receive the height of the table , but firstly we should determine the necessary width of our table. It will look like this:
float necessaryWidth = 523f; IRenderer tableRenderer = table.createRendererSubTree().setParent(doc.getRenderer()); LayoutResult tableLayoutResult = tableRenderer.layout(new LayoutContext(new LayoutArea(0, new Rectangle(necessaryWidth, 1000)))); float tableHeightTotal = tableLayoutResult.getOccupiedArea().getBBox().getHeight();
And then we can use received
tableHeightTotal in creating a new document and setting zero margins to our document:
Document doc2 = new Document(pdfDoc2, new PageSize(tableWidthTotal, tableHeightTotal)); doc2.setMargins(0,0,0,0); doc2.add(table);
Note that all measurements are done in user units and that one user unit equals 1 pt by default.
Click this link if you want to see how to answer this question in iText 5.