我下载了最新版本的 iTextSharp dll。我生成了一个 PdfPTable 对象,我必须设置它的高度。尽管设置了 PdfPTable 的宽度,但我无法设置它的高度。一些作者建议使用“setFixedHeight”方法。但是最后一个版本的 iTextSharp.dll 没有像“setFixedHeight”这样的方法。它的版本是 5.5.2。我该怎么做?
3 回答
一旦你开始考虑它,设置桌子的高度就没有意义了。或者,这是有道理的,但留下了许多未回答或无法回答的问题。例如,如果您将两行表格的高度设置为 500,这是否意味着每个单元格的高度为 250?如果将大图像放在第一行怎么办,表格是否应该通过拆分 400/100 来自动响应?那么两行中的大内容呢,它应该压扁那些吗?这些场景中的每一个都会产生不同的结果,这使得知道表实际上会做什么变得不可靠。如果您查看HTML 规范,您会发现它们甚至不允许为表格设置固定高度。
但是,有一个简单的解决方案,就是设置单元格本身的固定高度。只要您不使用new PdfPCell()
,您就可以设置DefaultCell.FixedHeight
为您想要的任何内容。
var t = new PdfPTable(2);
t.DefaultCell.FixedHeight = 100f;
t.AddCell("Hello");
t.AddCell("World");
t.AddCell("Hello");
t.AddCell("World");
doc.Add(t);
如果您手动创建单元格,则需要FixedHeight
在每个单元格上设置:
var t = new PdfPTable(2);
for(var i=0;i<4;i++){
var c = new PdfPCell(new Phrase("Hello"));
c.FixedHeight = 75f;
t.AddCell(c);
}
doc.Add(t);
但是,如果你想要正常的桌子并且必须设置一个固定的高度来切掉不适合的东西,你也可以使用ColumnText
. 我不会推荐这个,但你可能有一个案例。下面的代码将只显示六行。
var ct = new ColumnText(writer.DirectContent);
ct.SetSimpleColumn(100, 100, 200, 200);
var t = new PdfPTable(2);
for(var i=0;i<100;i++){
t.AddCell(i.ToString());
}
ct.AddElement(t);
ct.Go();
您可以使用以下任何一种
cell.MinimumHeight = 20f;
或者
cell.FixedHeight = 30f;
前提是你已经下载了jar iText jar,你可以试试这段代码,你可以实现这个功能,在一张A4纸上拿出一行三列数据例如:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
public class ceshi {
public static final String DEST = "D:\\fixed_height_cell.pdf";
public static void main(String[] args) throws IOException,
DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new ceshi().createPdf(DEST);
}
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
PdfPTable table = new PdfPTable(3);// Set a row and the three column of
// A4 paper
table.setWidthPercentage(100);
PdfPCell cell;
for (int r = 1; r <= 2; r++) {// Set display two lines
for (int c = 1; c <= 3; c++) {// Set to display a row of three columns
cell = new PdfPCell();
cell.addElement(new Paragraph("test"));
cell.setFixedHeight(285);// Control the fixed height of each cell
table.addCell(cell);
}
}
document.add(table);
document.close();
}
}