java 畫pdf用itext調整表格寬度、自定義各個列寬的方法
ps:我用的版本是7.0.5
場景:左側第一列寬度不夠,導致數據換行。
Table table = new Table(new float[2]);
new 一個Table之后,setWidthPercent()這個參數是這是所有列寬,并不能試用個別列。
需要在寫入數據的時候對各個列進行自定義列寬:
Cell cell=new Cell().setWidth(70).setBorder(Border.NO_BORDER).setHorizontalAlignment(HorizontalAlignment.RIGHT).add(new Paragraph(entry.getKey()).setFont(sysFont).setFontSize(10));Cell cell1=new Cell().setBorder(Border.NO_BORDER).setHorizontalAlignment(HorizontalAlignment.LEFT).add(new Paragraph(entry.getValue()).setFont(sysFont).setFontSize(10));
cell為第一列,cell1為第二列,在cell中設置寬度,不要再table上設置寬度。
即可解決個別列寬問題。
調整后的效果:補充: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 2017/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('http://www.baidu.com')); 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(); } } }
所以以后做功能,百度大法雖好,也要有自己的靈活性,遇到問題多角度解決,技術在更新,思路也要更新
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章: