我正在生成一个文件,就像下面的代码一样,除了表格的内容不同以外。我需要做的是确保该表的大小永远不会超过一页,而不考虑单元格中的内容数量。有没有办法做到这一点?如何调整PdfPTable的大小以适应页面?
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。我做错了什么,或者这是一个错误的方法吗?
试图评论,但我无法弄清楚如何在评论中正确插入代码,所以我编辑了这个问题。 – 2013-02-20 16:42:14
乍一看,您并未正确地将表格添加到模板中。我会尝试你的例子,看看出了什么问题。 – 2013-02-20 17:00:34
你在三个地方有定位错误。我已经用一种按需要工作的方法更新了我的答案。 – 2013-02-20 17:17:33