1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > java通过itext生成PDF 设置单元格cell的最大高度 以及 itext7初尝

java通过itext生成PDF 设置单元格cell的最大高度 以及 itext7初尝

时间:2022-02-21 21:05:13

相关推荐

java通过itext生成PDF 设置单元格cell的最大高度 以及 itext7初尝

网上百度java生成pdf都是很老的代码,使用的是itext5,找遍了大江南北都找不到设置表格或单元格最大高度,或者绝对定位表格的实现,最后对table和cell的方法一个一个找,找到了满足要求的方法:

cell.setMaxLines(int numberOfLines)

由于字体确定,每行字体的高度已确定,设定最大行数也就设定了最大高度,且避免了设置的高度不是每行高度的整数倍的麻烦,itext的这个操作也挺6,只是不符合一般认知,无法轻易找到这个方法。

虽然cell最大高度解决了,但是表格的绝对定位依然没有解决,itext5只能通过百分比的方式设置表格宽度,然后居中或靠左靠右显示,非常不灵活。

经查询,itext7是目前最新版,试用了一下,非常灵活,该解决的问题都解决了。用法与5有稍许区别。

iText7示例

import com.itextpdf.io.font.PdfEncodings;import com.itextpdf.kernel.color.Color;import com.itextpdf.kernel.font.PdfFont;import com.itextpdf.kernel.font.PdfFontFactory;import com.itextpdf.kernel.geom.PageSize;import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter;import com.itextpdf.kernel.pdf.action.PdfAction;import com.itextpdf.layout.Document;import com.itextpdf.layout.border.DashedBorder;import com.itextpdf.layout.element.Cell;import com.itextpdf.layout.element.Link;import com.itextpdf.layout.element.Paragraph;import com.itextpdf.layout.element.Table;/*** @author belle.wang* @version V1.0.0* @Description* @date /7/19 0019 上午 11:37*/public class Main {public static void main(String[] args) {try {PdfDocument pdfDoc = new PdfDocument(new PdfWriter("d:\\Helloworld.pdf"));Document document = new Document(pdfDoc, PageSize.A4);// 支持系统字体(支持中文)PdfFontFactory.registerSystemDirectories();PdfFont chinese = PdfFontFactory.createRegisteredFont("microsoft yahei", PdfEncodings.IDENTITY_H);// 文字Paragraph phrase = new Paragraph();phrase.setFont(chinese);phrase.add("雷猴啊");Link chunk = new Link("European Business Award!",PdfAction.createURI(""));phrase.add(chunk);// 图片// Image img = new Image(ImageDataFactory.create("src/main/resources/img/magic.png"));// img.setFixedPosition(80, 560);//有传页数参数的方法// 表格Table table = new Table(new float[]{200f, 100f});table.setWidth(300);table.setBorder(new DashedBorder(Color.BLUE, 2));table.setFixedPosition(300f,300f,300f);table.addCell(phrase);// The complete cell is a link:Cell cell = new Cell().add("Help us win a European Business Award!");table.addCell(cell);document.add(table);document.close();} catch (Exception e) {e.printStackTrace();}}}

所以以后做功能,百度大法虽好,也要有自己的灵活性,遇到问题多角度解决,技术在更新,思路也要更新

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。