我正在生成一个文档,如下面的代码所示,除了表格的内容,这些内容各不相同 . 我需要做的是确保此表的大小不会超过一页,无论单元格中的内容量如何 . 有办法吗?
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public void createTemplate() throws DocumentException, FileNotFoundException, IOException{
String TARGET = System.getProperty("user.home")+"\temp.pdf";
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(TARGET));
document.open();
PdfPTable table = new PdfPTable(7);
for (int i = 0; i < 105; i++) {
Phrase p = new Phrase("some text");
PdfPCell cell = new PdfPCell();
cell.addElement(p);
table.addCell(cell);
}
table.setTotalWidth(PageSize.A4.getWidth()-10);
table.setLockedWidth(true);
PdfContentByte canvas = writer.getDirectContent();
PdfTemplate template = canvas.createTemplate(table.getTotalWidth(),table.getTotalHeight());
table.writeSelectedRows(0, -1, 0, PageSize.A4.getHeight(), template);
Image img = Image.getInstance(template);
img.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
img.setAbsolutePosition(0, PageSize.A4.getHeight());
document.add(img);
document.close();
Desktop desktop = Desktop.getDesktop();
File file = new File(TARGET);
desktop.open(file); }
编辑:@Bruno Lowagie . 包含在图像中的模板提示听起来恰到好处,我改变了代码,但我现在得到的只是一个空PDF . 我做错了什么,或者这是一个错误的做法?
1 回答
如果您想要一个适合页面的表,您应该在考虑页面大小之前创建表,并在TableHeight示例中查询表的高度 . 请注意,除非您定义表的宽度,否则
getTotalHeight()
方法将返回0 . 这可以这样做:现在,您可以创建一个大小为
Rectangle(0, 0, width + margin * 2, getTotalHeight() + margin * 2)
的Document
,并且在使用writeSelectedRows()
方法添加文档时,该表应该完全符合文档 .如果您不想要自定义页面大小,则需要创建具有表大小的
PdfTemplate
并将表添加到此模板对象 . 然后将模板对象包装在Image
中,并使用scaleToFit()
来缩小表格的大小 .