Itext 7 生成pdf带有背景图并下载PDF到本地
引入jar包
<dependency><groupId>com.itextpdf</groupId><artifactId>itext7-core</artifactId><version>7.0.3</version><type>pom</type></dependency>
代码实现
@GetMapping(value = "itextPdfDownLoad")public void itextPdfDownLoad(HttpServletResponse response) throws IOException {response.reset();//设置文件编码response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("个人荣誉.PDF", "UTF-8"));response.setContentType("application/octet-stream;charset=UTF-8");OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());PageSize pageSize = PageSize.A4.rotate();PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outputStream));Document doc = new Document(pdfDoc, pageSize);float[] f = new float[]{0.01f};Table table = new Table(UnitValue.createPercentArray(f));table.setWidth(745);Cell cell = new Cell();//设置表格边框颜色 这里设置的是白色cell.setBorder(new SolidBorder(new DeviceRgb(0xFFF, 0xFFF, 0xFFF),3));//设置插入字体PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H",true);//背景图上写入汉字Paragraph p = new Paragraph("努尔哈赤").setFont(font).setFontSize(13f).setFontColor(DeviceGray.BLACK);//写入汉字坐标p.setFirstLineIndent(140f);p.setFixedLeading(418f);cell.add(p);//获取表格背景图URL resource = this.getClass().getClassLoader().getResource("honour.png");assert resource != null;Image img = new Image(ImageDataFactory.create(resource.getPath()));cell.setNextRenderer(new ImageBackgroundCellRenderer(cell, img));cell.setHeight(590 * img.getImageHeight() / img.getImageWidth());table.addCell(cell);doc.add(table);doc.close();outputStream.flush();}
实现效果