java生成pdf在样式方面是有一定的局限性的,这种一般作为前端处理不了,需要后端自己处理的补充。
咱们先把需要的包依赖引入一下
<!--导出pdf所需包-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>5.1.0</version>
</dependency><!--生成条形码所需包-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
把需要的包引入后把需要的方法贴上,这个只是我使用的模板,你们要用的话可以稍微改下表格或样式。
package jnpf.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jnpf.service.PdfDownService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
/**
* @ClassName : pdfTestController
* @Description : pdf
* @Author : tuchen
* @Date: 2024-06-26 14:09
*/
@RestController
@RequestMapping("/getPdf")
public class pdfTestController {
@Autowired
private PdfDownService fumigationService;
@GetMapping("/download")
public void download(HttpServletResponse response, HttpServletRequest request) throws IOException {
// 防止日志记录获取session异常
request.getSession();
// 设置编码格式
response.setContentType("application/pdf;charset=UTF-8");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("下载的PDF名称", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".pdf");
fumigationService.download(response);
}
}
package jnpf.service.impl;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import jnpf.service.PdfDownService;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.stereotype.Service;
import jnpf.util.PdfPageUtil;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* @ClassName : PdfDownServcieImpl
* @Description : pdf
* @Author : tuchen
* @Date: 2024-06-26 16:30
*/
@Service
public class PdfDownServcieImpl implements PdfDownService {
@Override
public void download(HttpServletResponse response) throws IOException {
//要下载的数据查询数据部分我去掉了有需要自己根据业务取
// 定义全局的字体静态变量
Font titlefont;
Font headfont;
Font keyfont = null;
Font textfont = null;
Font content = null;
// 最大宽度
try {
// 不同字体(这里定义为同一种字体:包含不同字号、不同style)
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 16, Font.BOLD);
headfont = new Font(bfChinese, 14, Font.BOLD);
keyfont = new Font(bfChinese, 10, Font.BOLD);
textfont = new Font(bfChinese, 15, Font.NORMAL);
content = new Font(bfChinese, 10, Font.NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
BaseFont bf;
Font font = null;
try {
//创建字体
bf = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);
//使用字体并给出颜色
font = new Font(bf,25,Font.BOLD,BaseColor.BLACK);
} catch (Exception e) {
e.printStackTrace();
}
Document document = new Document(new RectangleReadOnly(842F, 595F));
//设置页边距 60:左边距,60:右边距,72:上边距,72:下边距
document.setMargins(60, 40, 40, 40);
try {
PdfWriter writer = PdfWriter.getInstance(document,response.getOutputStream());
//添加页码
writer.setPageEvent(new PdfPageUtil());
//打开生成的pdf文件
document.open();
float [] width = {120f,20f};
PdfPTable titleTable = new PdfPTable(width); // 创建一个5列的表格
titleTable.setWidthPercentage(100);
Paragraph title = new Paragraph("打印单",font);
PdfPCell titleHeaderCell = creatframelessCenterCell("",null);
titleHeaderCell.setPhrase(title);
titleTable.addCell(titleHeaderCell);
//设置内容
String fileName = "zd123456";
String path = "D:\\project\\test\\Pdf\\PdfDev\\src\\main\\resources\\barcode\\barCode.png";
createBarCode(path,"123576436543");
//加载条形码
Image barCodeImage = PdfPageUtil.loadingPicture(path);
barCodeImage.scaleAbsolute(600, 200);
PdfPCell imgCell = PdfPageUtil.getBodyPdfPCell_image();
//imgCell.setRowspan(1);
//imgCell.setColspan(2);
imgCell.setPhrase(new Paragraph(new Chunk(barCodeImage, 0, 0)));
//imgCell.disableBorderSide(11);
//添加条形码
titleTable.addCell(imgCell);
//设置上部分内容
// 创建一个PdfPTable对象,指定列数
PdfPTable tableHeaad = new PdfPTable(6); // 创建一个3列的表格
tableHeaad.setWidthPercentage(100);
//第一行
PdfPCell headerCell = creatframelessCell("组织:",content);
tableHeaad.addCell(headerCell);
headerCell = creatBottomBordeCell("轮回殿",content);
tableHeaad.addCell(headerCell);
headerCell = creatframelessCell("单据号:",content);
tableHeaad.addCell(headerCell);
headerCell = creatBottomBordeCell("蛟三",content);
tableHeaad.addCell(headerCell);
headerCell = creatframelessCell("日期:",content);
tableHeaad.addCell(headerCell);
headerCell = creatBottomBordeCell("2024-6-27",content);
tableHeaad.addCell(headerCell);
//第二行
headerCell = creatframelessCell("经办人:",content);
tableHeaad.addCell(headerCell);
headerCell = creatBottomBordeCell("韩立",content);
tableHeaad.addCell(headerCell);
headerCell = creatframelessCell("经办部门:",content);
tableHeaad.addCell(headerCell);
headerCell = creatBottomBordeCell("北寒仙域",content);
tableHeaad.addCell(headerCell);
headerCell = creatframelessCell("币种:",content);
tableHeaad.addCell(headerCell);
headerCell = creatBottomBordeCell("人民币",content);
tableHeaad.addCell(headerCell);
//第三行
headerCell = creatframelessCell("合计金额:",content);
tableHeaad.addCell(headerCell);
headerCell = creatBottomBordeCell("251",content);
tableHeaad.addCell(headerCell);
headerCell = creatframelessCell("合计金额(大写):",content);
tableHeaad.addCell(headerCell);
headerCell = creatBottomBordeCell("贰佰伍拾壹元整",content);
tableHeaad.addCell(headerCell);
headerCell = creatframelessCell("事由:",content);
tableHeaad.addCell(headerCell);
headerCell = creatBottomBordeCell("测试",content);
tableHeaad.addCell(headerCell);
//第四行
headerCell = creatframelessCell("备注:",content);
tableHeaad.addCell(headerCell);
headerCell = new PdfPCell(new Paragraph("",content));
tableHeaad.addCell(headerCell);
headerCell = new PdfPCell(new Paragraph("",content));
tableHeaad.addCell(headerCell);
headerCell.setBorder(0);
PdfPCell expenseCell = null;
// 设置表格的列宽和列数
//费用报销信息
PdfPTable expenseTable = new PdfPTable(6); // 创建一个⑥列的表格
expenseTable.setWidthPercentage(100);
expenseTable.setWidths(
new float [] {12,30,16,16,16,16}
);
expenseCell = creatUndertoneCell("类型",content);
expenseTable.addCell(expenseCell);
expenseCell = creatUndertoneCell("部门",content);
expenseTable.addCell(expenseCell);
expenseCell = expenseCell = creatUndertoneCell("业务金额",content);
expenseTable.addCell(expenseCell);
expenseCell = creatUndertoneCell("金额",content);
expenseTable.addCell(expenseCell);
expenseCell = expenseCell = creatUndertoneCell("其他金额",content);
expenseTable.addCell(expenseCell);
expenseCell = expenseCell = creatUndertoneCell("总金额",content);
expenseTable.addCell(expenseCell);
//信息
PdfPCell zdExpenseCell = null;
PdfPTable zdExpenseTable = new PdfPTable(7); // 创建一个⑥列的表格
zdExpenseTable.setWidthPercentage(100);
//列表-第四行
zdExpenseCell = creatUndertoneCell("人数",content);
zdExpenseCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
zdExpenseCell.setHorizontalAlignment(Element.ALIGN_CENTER);
zdExpenseCell.setFixedHeight(20);
zdExpenseTable.addCell(zdExpenseCell);
zdExpenseCell = creatUndertoneCell("人数",content);
zdExpenseCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
zdExpenseCell.setHorizontalAlignment(Element.ALIGN_CENTER);
zdExpenseTable.addCell(zdExpenseCell);
zdExpenseCell = creatUndertoneCell("金额",content);
zdExpenseCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
zdExpenseCell.setHorizontalAlignment(Element.ALIGN_CENTER);
zdExpenseTable.addCell(zdExpenseCell);
zdExpenseCell = creatUndertoneCell("金额",content);
zdExpenseCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
zdExpenseCell.setHorizontalAlignment(Element.ALIGN_CENTER);
zdExpenseTable.addCell(zdExpenseCell);
zdExpenseCell = creatUndertoneCell("数量",content);
zdExpenseCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
zdExpenseCell.setHorizontalAlignment(Element.ALIGN_CENTER);
zdExpenseTable.addCell(zdExpenseCell);
zdExpenseCell = creatUndertoneCell("金额",content);
zdExpenseCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
zdExpenseCell.setHorizontalAlignment(Element.ALIGN_CENTER);
zdExpenseTable.addCell(zdExpenseCell);
zdExpenseCell = creatUndertoneCell("数量",content);
zdExpenseCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
zdExpenseCell.setHorizontalAlignment(Element.ALIGN_CENTER);
zdExpenseTable.addCell(zdExpenseCell);
PdfPCell payInfoCell = null;
PdfPTable payInfoTable = new PdfPTable(9); // 创建一个⑥列的表格
payInfoTable.setWidthPercentage(100);
//支付信息
payInfoCell = creatUndertoneCell("方式",content);
payInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
payInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
payInfoCell.setFixedHeight(20);
payInfoTable.addCell(payInfoCell);
payInfoCell = creatUndertoneCell("金额",content);
payInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
payInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
payInfoTable.addCell(payInfoCell);
payInfoCell = creatUndertoneCell("名称",content);
payInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
payInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
payInfoTable.addCell(payInfoCell);
payInfoCell = creatUndertoneCell("账号",content);
payInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
payInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
payInfoTable.addCell(payInfoCell);
payInfoCell = creatUndertoneCell("支付方",content);
payInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
payInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
payInfoTable.addCell(payInfoCell);
payInfoCell = creatUndertoneCell("名称",content);
payInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
payInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
payInfoTable.addCell(payInfoCell);
payInfoCell = creatUndertoneCell("账号",content);
payInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
payInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
payInfoTable.addCell(payInfoCell);
payInfoCell = creatUndertoneCell("收款方",content);
payInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
payInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
payInfoTable.addCell(payInfoCell);
payInfoCell = creatUndertoneCell("备注",content);
payInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
payInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
payInfoTable.addCell(payInfoCell);
//审批信息
PdfPCell approveInfoCell = null;
PdfPTable approveInfoTable = new PdfPTable(4); // 创建一个⑥列的表格
approveInfoTable.setWidthPercentage(100);
approveInfoCell = creatUndertoneCell("审批人",content);
approveInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
approveInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
approveInfoTable.addCell(approveInfoCell);
approveInfoCell = creatUndertoneCell("审批节点",content);
approveInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
approveInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
approveInfoTable.addCell(approveInfoCell);
approveInfoCell = creatUndertoneCell("审批时间",content);
approveInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
approveInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
approveInfoTable.addCell(approveInfoCell);
approveInfoCell = creatUndertoneCell("审批意见",content);
approveInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
approveInfoCell.setHorizontalAlignment(Element.ALIGN_CENTER);
approveInfoTable.addCell(approveInfoCell);
PdfPTable printInfoTable = new PdfPTable(2); // 创建一个⑥列的表格
PdfPCell printPerson = PdfPageUtil.getBodyPdfPCell_left();
printPerson.setRowspan(1);
printPerson.setColspan(1);
printPerson.setFixedHeight(30);
printPerson.setBorder(0); // 设置单元格无边框
printPerson.setPhrase(new Paragraph("打印人: 管里员", PdfPageUtil.getPdfBodyFont()));
printInfoTable.addCell(printPerson);
// 专家
PdfPCell printDate = PdfPageUtil.getBodyPdfPCell_right();
printDate.setRowspan(1);
printDate.setColspan(2);
printDate.setFixedHeight(30);
printDate.setBorder(0); // 设置单元格无边框
printDate.setPhrase(new Paragraph("打印日期: 2024-06-30", PdfPageUtil.getPdfBodyFont()));
printInfoTable.addCell(printDate);
//引用字体
// document.add(grid);
document.add(titleTable);
document.add(new Paragraph("\n"));
document.add(tableHeaad);
document.add(new Paragraph("\n"));
document.add(new Paragraph("信息行1",content));
document.add(new Paragraph("\n"));
document.add(expenseTable);
document.add(new Paragraph("\n"));
document.add(new Paragraph("信息行2",content));
document.add(new Paragraph("\n"));
document.add(zdExpenseTable);
document.add(new Paragraph("\n"));
document.add(new Paragraph("信息行3",content));
document.add(new Paragraph("\n"));
document.add(payInfoTable);
document.add(new Paragraph("\n"));
document.add(new Paragraph("审批信息",content));
document.add(new Paragraph("\n"));
document.add(approveInfoTable);
document.add(printInfoTable);
//关闭文档
document.close();
} catch (DocumentException e) {
e.printStackTrace();
System.out.println("导出pdf失败");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void createBarCode(String path,String data) throws IOException {
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(data, BarcodeFormat.CODE_39, 200, 50);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", new File(path).toPath());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Description:创建边框浅色内容居中单元格
* @param
* @return: com.itextpdf.text.pdf.PdfPCell
* @Author: tuchen
* @Date 2024/6/29 13:53
*/
public PdfPCell creatUndertoneCell (String comment,Font content){
PdfPCell cell = new PdfPCell(new Paragraph(comment,content));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setUseAscender(true);
cell.setUseDescender(true);
cell.setFixedHeight(30);
cell.setBorderColor(new BaseColor(200,200,200));
return cell;
}
/**设置下边框单元格
* @Description:
* @param comment
* @param content
* @return: com.itextpdf.text.pdf.PdfPCell
* @Author: tuchen
* @Date 2024/6/29 14:46
*/
public PdfPCell creatBottomBordeCell (String comment,Font content){
PdfPCell cell = new PdfPCell(new Paragraph(comment,content));
cell.setBorder(Rectangle.BOTTOM);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_BASELINE);
return cell;
}
/**
* @Description:无边框内容靠左单元格
* @param comment
* @param content
* @return: com.itextpdf.text.pdf.PdfPCell
* @Author: tuchen
* @Date 2024/6/29 14:44
*/
public PdfPCell creatframelessCell (String comment,Font content){
PdfPCell cell = new PdfPCell(new Paragraph(comment,content));
cell.setBorder(0); // 设置单元格无边框
cell.setPadding(5); // 设置单元格内边距
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_BASELINE);
cell.setBorderColor(new BaseColor(200,200,200));
return cell;
}
/**
* @Description:无边框内容居中单元格
* @param comment
* @param content
* @return: com.itextpdf.text.pdf.PdfPCell
* @Author: tuchen
* @Date 2024/6/29 14:44
*/
public PdfPCell creatframelessCenterCell (String comment,Font content){
PdfPCell cell = new PdfPCell(new Paragraph(comment,content));
cell.setBorder(0); // 设置单元格无边框
cell.setPadding(0); // 设置单元格内边距
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setFixedHeight(40);
cell.setUseAscender(true);
cell.setUseDescender(true);
cell.setBorderColor(new BaseColor(200,200,200));
return cell;
}
/**
* @Description:获取图片单元格
* @param iamgeBytes
* @param high
* @return: com.itextpdf.text.pdf.PdfPCell
* @Author: tuchen
* @Date 2024/6/30 11:43
*/
/* private PdfPCell mircoSoftFont(byte[] iamgeBytes, int high) throws Exception {
byte[] fileByte = toByteArray("D:\\2.jpg");
Jpeg jpeg = new Jpeg(fileByte);
jpeg.scaleAbsolute(70, 50);
PdfPCell pdfPCell = new PdfPCell(jpeg);
pdfPCell.setMinimumHeight(high);
pdfPCell.setUseAscender(true); // 设置可以居中
pdfPCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // 设置水平居中
pdfPCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE); // 设置垂直居中
return pdfPCell;
}
*/
}
package jnpf.service;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @ClassName : PdfDownService
* @Description : pdf
* @Author : tuchen
* @Date: 2024-06-26 16:29
*/
public interface PdfDownService {
void download(HttpServletResponse response) throws IOException;
}
转换的工具类
package jnpf.util;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.*;
import java.net.MalformedURLException;
/**
* @Author xx
* @Date 2023/12/15 10:05
* @Description: 导出pdf添加页数
* @Version 1.0
*/
public class PdfPageUtil extends PdfPageEventHelper {
/**
* 页眉
*/
//public String header = "itext测试页眉";
/**
* 文档字体大小,页脚页眉最好和文本大小一致
*/
public int presentFontSize = 15;
/**
* 文档页面大小,最好前面传入,否则默认为A4纸张
*/
public Rectangle pageSize = PageSize.A4;
// 模板
public PdfTemplate total;
// 基础字体对象
public BaseFont bf = null;
// 利用基础字体生成的字体对象,一般用于生成中文文字
public Font fontDetail = null;
/**
*
* 无参构造方法.
*
*/
public PdfPageUtil() {
}
/**
*
* 构造方法.
*
* @param
*
* @param presentFontSize
* 数据体字体大小
* @param pageSize
* 页面文档大小,A4,A5,A6横转翻转等Rectangle对象
*/
public PdfPageUtil( int presentFontSize, Rectangle pageSize) {
this.presentFontSize = presentFontSize;
this.pageSize = pageSize;
}
public void setPresentFontSize(int presentFontSize) {
this.presentFontSize = presentFontSize;
}
/**
*
* 文档打开时创建模板
*/
@Override
public void onOpenDocument(PdfWriter writer, Document document) {
// 共 页 的矩形的长宽高
total = writer.getDirectContent().createTemplate(50, 50);
}
/**
*
*关闭每页的时候,写入页眉,写入'第几页共'这几个字。
*/
@Override
public void onEndPage(PdfWriter writer, Document document) {
this.addPage(writer, document);
}
//加分页
public void addPage(PdfWriter writer, Document document){
//设置分页页眉页脚字体
try {
if (bf == null) {
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
}
if (fontDetail == null) {
fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 1.写入页眉
// ColumnText.showTextAligned(writer.getDirectContent(),
// Element.ALIGN_LEFT, new Phrase(header, fontDetail),
// document.left(), document.top() + 20, 0);
// 2.写入前半部分的 第 X页/共
int pageS = writer.getPageNumber();
//String foot1 = "第 " + pageS + " 页 /共";
String foot1 = pageS +"/";
Phrase footer = new Phrase(foot1, fontDetail);
// 3.计算前半部分的foot1的长度,后面好定位最后一部分的'Y页'这俩字的x轴坐标,字体长度也要计算进去 = len
float len = bf.getWidthPoint(foot1, presentFontSize);
// 4.拿到当前的PdfContentByte
PdfContentByte cb = writer.getDirectContent();
// 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F
ColumnText
.showTextAligned(
cb,
Element.ALIGN_CENTER,
footer,
(document.rightMargin() + document.right()
+ document.leftMargin() - document.left() - len) / 2.0F ,
document.bottom() - 10, 0);
cb.addTemplate(total, (document.rightMargin() + document.right()
+ document.leftMargin() - document.left()) / 2.0F ,
document.bottom() - 10); // 调节模版显示的位置
}
// //加水印
// public void addWatermark(PdfWriter writer){
// // 水印图片
// Image image;
// try {
// image = Image.getInstance("./web/images/001.jpg");
// PdfContentByte content = writer.getDirectContentUnder();
// content.beginText();
// // 开始写入水印
// for(int k=0;k<5;k++){
// for (int j = 0; j <4; j++) {
// image.setAbsolutePosition(150*j,170*k);
// content.addImage(image);
// }
// }
// content.endText();
// } catch (IOException | DocumentException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
/**
*
* 关闭文档时,替换模板,完成整个页眉页脚组件
*/
@Override
public void onCloseDocument(PdfWriter writer, Document document) {
// 关闭文档的时候,将模板替换成实际的 Y 值
total.beginText();
// 生成的模版的字体、颜色
total.setFontAndSize(bf, presentFontSize);
//页脚内容拼接 如 第1页/共2页
//String foot2 = " " + (writer.getPageNumber()) + " 页";
//页脚内容拼接 如 第1页/共2页
String foot2 = String.valueOf(writer.getPageNumber());
// 模版显示的内容
total.showText(foot2);
total.endText();
total.closePath();
}
// 生成空表格
public static PdfPCell getEmptyCell() throws Exception {
PdfPCell pdfPCell = getBodyPdfPCell_center();
pdfPCell.setPhrase(new Paragraph(" ", getPdfBodyFont()));
return pdfPCell;
}
// 设置表体的表格样式 字体居右
public static PdfPCell getBodyPdfPCell_right() {
PdfPCell pdfPCell = new PdfPCell();
pdfPCell.setMinimumHeight(12);
pdfPCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
return pdfPCell;
}
// 设置表体的表格样式 字体居左
public static PdfPCell getBodyPdfPCell_left() {
PdfPCell pdfPCell = new PdfPCell();
pdfPCell.setMinimumHeight(12);
pdfPCell.setHorizontalAlignment(Element.ALIGN_LEFT);
pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
return pdfPCell;
}
public static PdfPCell getBodyPdfPCell_image() {
PdfPCell pdfPCell = new PdfPCell();
pdfPCell.setMinimumHeight(40);
pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
pdfPCell.setBorder(0);
return pdfPCell;
}
// 设置表体的表格样式 字体居左
public static PdfPCell getBodyPdfPCell_left_top() {
PdfPCell pdfPCell = new PdfPCell();
pdfPCell.setMinimumHeight(12);
pdfPCell.setHorizontalAlignment(Element.ALIGN_LEFT);
pdfPCell.setVerticalAlignment(Element.ALIGN_TOP);
return pdfPCell;
}
// 设置表体的表格样式 字体居中
public static PdfPCell getBodyPdfPCell_center() {
PdfPCell pdfPCell = new PdfPCell();
pdfPCell.setMinimumHeight(12);
pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
return pdfPCell;
}
// 设置表头
public static Font getPdfTitleFont() throws Exception {
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 14F, Font.NORMAL);
fontChinese.setStyle("bold");
return fontChinese;
}
// 设置表体
public static Font getPdfBodyFont() throws Exception {
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 10F, Font.NORMAL);
return fontChinese;
}
// 设置表体-字体加粗
public static Font getPdfBodyFont_bold() throws Exception {
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 8.5F, Font.NORMAL);
fontChinese.setStyle("bold");
return fontChinese;
}
// 设置下划线 -> 内容下方
public static Chunk setUnderlineBlank(String content, float thickness, float yPosition) throws Exception {
Chunk chunk = new Chunk(content, PdfPageUtil.getPdfBodyFont());
chunk.setUnderline(thickness, yPosition);
return chunk;
}
public static Image loadingPicture(String filePath) throws BadElementException, MalformedURLException, IOException {
File file = new File(filePath);
byte[] by = File2byte(file);
Image image = Image.getInstance(by);
image.scaleAbsolute(60, 20);// 调整图片大小(宽度 高度)
return image;
}
private static byte[] File2byte(File tradeFile) {
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(tradeFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
}
加好之后本地启动服务,请求配置的路径 /getPdf/download,也可以直接转成输出流和baes64
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// 将字节数组转换为Base64字符串
byte[] pdfBytes = outputStream.toByteArray();
base64Pdf = Base64.getEncoder().encodeToString(pdfBytes);
这样的话得把response.getOutputStream(),这个改成自己new的输出流。
PdfWriter writer = PdfWriter.getInstance(document,outputStream);
求点赞加关注哦~