IText生成PDF
程序员文章站
2024-03-24 11:46:58
...
1.pom.xml
<dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>4.2.2</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.4.3</version> </dependency>
2.java
//【1】初始化
Document document = new Document(PageSize.A4.rotate());
//【2】使用PdfWriter进行写文件操作
PdfWriter writer = PdfWriter.getInstance(document,response.getOutputStream());//写入流中
document.open();
//【3】设置页眉页脚
PdfReportM1HeaderFooter footer=new PdfReportM1HeaderFooter();
footer.onOpenDocument(writer,document);
writer.setPageEvent(footer);
// 【4】中文字体
BaseFont bfChinese =BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 9, Font.NORMAL);
// 【5】创建表格
PdfPTable datatable1 = new PdfPTable(3);//列数
int[] cellsWidth1 = {1,1,1};//列宽
tableBaseConf(spacing, padding, datatable1, cellsWidth1);
datatable1.addCell(new Paragraph("供应公司名称:" + deliveryMap.get("supName"), fontChinese));
datatable1.addCell(new Paragraph("HRP订单编号:" + deliveryMap.get("ext_order_id"), fontChinese));
datatable1.addCell(new Paragraph("配货时间:" + deliveryMap.get("deliveryDate"), fontChinese));
//【6】文字段落
Font fontChinese2 = new Font(bfChinese,16, Font.NORMAL);//16字体大小
Paragraph paragraph=new Paragraph(10f,"文字内容", fontChinese);//10f段落行间距
Font font=new Font();
font.setSize(6f);
paragraph.setFont(font);
paragraph.setAlignment(Element.ALIGN_LEFT);//段落文字左对齐
paragraph.setSpacingAfter(1f);//段落后间距
//【7】条形码
PdfContentByte cb = writer.getDirectContent();
Barcode128 code128 = new Barcode128();
code128.setCode("123456");
code128.setCodeType(Barcode.EAN8);
code128.setBarHeight(26f);//24
code128.setX(2f);
//code128.setAltText("wenzi");
code128.setFont(null);
Image p_w_picpath=code128.createImageWithBarcode(cb, null, null);
p_w_picpath.setAlignment(Image.MIDDLE);
document.add(datatable1);
document.add(paragraph);
document.add(p_w_picpath);
document.newPage();
转载于:https://blog.51cto.com/zuohao1990/1958427
上一篇: Flex开门效果