引入
@Autowired
private HttpServletResponse response;
@Autowired
private HttpServletRequest request;
实现类导出单个word
点击查看代码
public void exportStudentWordOld(JcsjLxxsxxDTO jcsjLxxsxxDTO){
String schoolName = jcsjLxxsglVOMapper.querySchoolName();
OutputStream outputStream = null;
BufferedInputStream bis = null;
try{
String realPath = request.getSession().getServletContext().getRealPath("");
String fileName = jcsjLxxsxxDTO.getXh() + "_"+jcsjLxxsxxDTO.getXm()+"离校报告单信息.doc";
String filePath = realPath + "/" + fileName;
response.setContentType("multipart/form-data");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName));
outputStream = response.getOutputStream();
List<JcsjLxxsglVO> jcsjLxxsglVOList= jcsjLxxsglVOMapper.selectStudentLeavingInfo(jcsjLxxsxxDTO);
Integer i = 0;
JcsjLxxsglVO jcsjLxxsglVO = jcsjLxxsglVOList.get(0);
//查询学生离校流程信息
List<LcglLchjPrintVO>lcglLchjPrintVOS = jcsjLxxsglVOMapper.selectLcxxByXh(jcsjLxxsglVO.getXh());
if(CollectionUtils.isNotEmpty(lcglLchjPrintVOS) && lcglLchjPrintVOS.size()>0 && !ObjectUtils.isEmpty(lcglLchjPrintVOS.get(0))){
jcsjLxxsglVO.setHjxxList(lcglLchjPrintVOS);
}
i++;
Document document = new Document(PageSize.A4);
RtfWriter2 rtfWriter2 = RtfWriter2.getInstance(document,new FileOutputStream(filePath));
document.open();
StudentLeavingWord studentLeavingWord = new StudentLeavingWord();
studentLeavingWord.leavingWordTemplate(document,jcsjLxxsglVO,schoolName,jcsjLxxsxxDTO.getExportType());
document.close();
if (rtfWriter2 != null) {
rtfWriter2.close();
}
File file = new File(filePath);
try {
bis = new BufferedInputStream(new FileInputStream(filePath));
int len = 0;
byte[] buffer = new byte[1024];
while ((len = bis.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
} catch (Exception e) {
log.error("context", e);
} finally {
if (file.exists()) {
boolean delete = file.delete();
if (!delete) {
log.error("context", file.getName()+"删除失败");
}
}
}
outputStream.flush();
}catch (Exception e) {
log.error("导出word失败的原因是:" + e);
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
实现类zip里面word转pdf
点击查看代码
public void exportStudentWord(JcsjLxxsxxDTO jcsjLxxsxxDTO){
String schoolName = jcsjLxxsglVOMapper.querySchoolName();
String downloadName = jcsjLxxsxxDTO.getXh() + "_"+jcsjLxxsxxDTO.getXm()+"离校报告单导出.zip";
String filePath = request.getSession().getServletContext().getRealPath("/");
response.setContentType("application/zip;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + Encodes.urlEncode(downloadName));
try (
OutputStream outputStream = response.getOutputStream();
ZipOutputStream zos = new ZipOutputStream(outputStream)
) {
String fileName = jcsjLxxsxxDTO.getXh() + "_"+jcsjLxxsxxDTO.getXm()+"离校报告单信息.doc";
File outFilePath = new File(filePath + "/" + fileName);
File outFile = new File(filePath + "/" + fileName);
byte[] buffer = new byte[1024];
int len = 0;
ZipEntry zipEntry = new ZipEntry(fileName);
BufferedInputStream bufferedInputStream = null;
BufferedInputStream bis = null;
try {
List<JcsjLxxsglVO> jcsjLxxsglVOList= jcsjLxxsglVOMapper.selectStudentLeavingInfo(jcsjLxxsxxDTO);
Integer i = 0;
JcsjLxxsglVO jcsjLxxsglVO = jcsjLxxsglVOList.get(0);
//查询学生离校流程信息
List<LcglLchjPrintVO>lcglLchjPrintVOS = jcsjLxxsglVOMapper.selectLcxxByXh(jcsjLxxsglVO.getXh());
if(CollectionUtils.isNotEmpty(lcglLchjPrintVOS) && lcglLchjPrintVOS.size()>0 && !ObjectUtils.isEmpty(lcglLchjPrintVOS.get(0))){
jcsjLxxsglVO.setHjxxList(lcglLchjPrintVOS);
}
i++;
Document document = new Document(PageSize.A4);
RtfWriter2 rtfWriter2 = RtfWriter2.getInstance(document,new FileOutputStream(outFilePath));
document.open();
StudentLeavingWord studentLeavingWord = new StudentLeavingWord();
studentLeavingWord.leavingWordTemplate(document,jcsjLxxsglVO,schoolName,jcsjLxxsxxDTO.getExportType());
document.close();
if (rtfWriter2 != null) {
rtfWriter2.close();
}
bis = new BufferedInputStream(new FileInputStream(outFile));
// bufferedInputStream = new BufferedInputStream(new FileInputStream(outFile));
// 这里是导出word
if (!"pdf".equals(jcsjLxxsxxDTO.getExportType())) {
zos.putNextEntry(zipEntry);
while ((len = bis.read(buffer)) != -1) {
zos.write(buffer, 0, len);
}
}
if ("pdf".equals(jcsjLxxsxxDTO.getExportType())) {
// 这里是doc转pdf, 但转出来的在linux里面字体有问题
Consumer<Writer> consumer = writer1 -> {
try {
writer1.write(Common.fileToCharArray(outFile));
} catch (IOException e) {
log.error("转化为pdf失败:{}", e);
throw new RuntimeException(e);
}
};
PdfUtil.wordToPdf(zos, "学生证明", consumer);
}
} catch (FileNotFoundException | TemplateException e) {
log.error("context", e);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != bufferedInputStream) {
bufferedInputStream.close();
}
if (outFile.exists()) {
if (!outFile.delete()) {
log.info("删除失败!");
}
}
}
}catch (IOException e) {
log.error("context", e);
}
}
工具类画word
点击查看代码
package com.ly.education.leaving.server.util;
import com.itextpdf.text.BaseColor;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPCell;
import com.ly.education.leaving.api.vo.basicData.JcsjLxxsglVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ObjectUtils;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class StudentLeavingWord {
/**
* 文件路径
*/
public static final String FILE_TEMPLATE_PATH = "file/已办理.png";
public void leavingWordTemplate(Document document, JcsjLxxsglVO jcsjLxxsglVO, String schoolName,String exportType)throws DocumentException, IOException {
BaseFont bfChinese = BaseFont.createFont();
Font contextBoldFont0 = new Font(bfChinese,10,Font.NORMAL);
Font contextBoldFont = new Font(bfChinese,12,Font.HELVETICA);
Font contextBoldFont1 = new Font(bfChinese,12,Font.HELVETICA);
Font contextBoldFont2 = new Font(bfChinese,10,Font.HELVETICA);
Font zysxFontBl = FontFactory.getFont("Helvetica", 8, Color.RED);
Font zysxFontBlueBl = FontFactory.getFont("Helvetica", 8, Color.BLUE);
// Font zysxFont = new Font(bfChinese,8,Font.NORMAL);
Font zysxrqFont = new Font(bfChinese,8,Font.NORMAL, Color.black);
Table table = new Table(2);
int[] widths = new int[]{37,57};
table.setWidths(widths);
table.setWidth(94);
table.setAutoFillEmptyCells(false);
table.setOffset(0f);
table.setPadding(8f);
String titleDetail = schoolName;
if(StringUtils.isBlank(jcsjLxxsglVO.getLxdttms())){
// schoolName +jcsjLxxsglVO.getBynf()+"年"+jcsjLxxsglVO.getByyf()+"月毕业研究生离校单"
titleDetail = titleDetail + "毕业研究生离校单";
}else{
titleDetail = titleDetail + jcsjLxxsglVO.getLxdttms();
}
// 读入流程名称的离校头部描述
Cell cell0 = new Cell(
new Phrase(titleDetail,
FontFactory.getFont(FontFactory.HELVETICA,16,new Color(0, 0, 0, 252))));
cell0.setColspan(2);
cell0.setHorizontalAlignment(Element.ALIGN_CENTER);
cell0.setBorderColor(Color.WHITE);
table.addCell(cell0);
document.add(table);
Paragraph pt0 = new Paragraph("恭喜您完成研究生学业,通过学位论文答辩,顺利毕业。请到以下部门办理离校手续。祝您毕业快乐,前程似锦,母校欢迎您常回来看看。",contextBoldFont0);
pt0.setAlignment(0);
pt0.setIndentationLeft(20);// 左缩进
pt0.setIndentationRight(20);// 右缩进
pt0.setFirstLineIndent(24);// 首行缩进
pt0.setLeading(20f);// 行间距
pt0.setSpacingBefore(2f);// 设置上空白
// pt0.setSpacingAfter(5f);// 设置段落下空白
document.add(pt0);
// Paragraph pt1 = new Paragraph("学生端:查看环节情况。导出离校单。",contextBoldFont0);
// pt1.setAlignment(0);
// pt1.setIndentationLeft(20);// 左缩进
// pt1.setIndentationRight(20);// 右缩进
// pt1.setFirstLineIndent(24);// 首行缩进
// pt1.setLeading(20f);// 行间距
// pt1.setSpacingBefore(5f);// 设置上空白
// pt1.setSpacingAfter(5f);// 设置段落下空白
// document.add(pt1);
Table table1 = new Table(6);
int[] widths1 = new int[]{15,16,15,16,15,17};
table1.setWidths(widths1);
table1.setWidth(94);
table1.setAutoFillEmptyCells(false);
table1.setCellsFitPage(true);
Cell cell1 = new Cell(new Phrase("姓名",contextBoldFont));
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
cell1.setVerticalAlignment(Element.ALIGN_CENTER);
cell1.setColspan(1);
cell1.setRowspan(1);
table1.addCell(cell1);
Cell cell2 = new Cell(new Phrase(jcsjLxxsglVO.getXm(),contextBoldFont));
cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
cell2.setVerticalAlignment(Element.ALIGN_CENTER);
cell2.setColspan(1);
cell2.setRowspan(1);
table1.addCell(cell2);
Cell cell3 = new Cell(new Phrase("学院",contextBoldFont));
cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
cell3.setVerticalAlignment(Element.ALIGN_CENTER);
cell3.setColspan(1);
cell3.setRowspan(1);
table1.addCell(cell3);
Cell cell4 = new Cell(new Phrase(jcsjLxxsglVO.getBmmc(),contextBoldFont2));
// Cell cell4 = new Cell(new Phrase("马克思主义学院学院啦",contextBoldFont2));
cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
cell4.setVerticalAlignment(Element.ALIGN_CENTER);
cell4.setColspan(1);
cell4.setRowspan(1);
table1.addCell(cell4);
Cell cell5 = new Cell(new Phrase("学科/专业",contextBoldFont));
cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
cell5.setVerticalAlignment(Element.ALIGN_CENTER);
cell5.setColspan(1);
cell5.setRowspan(1);
table1.addCell(cell5);
Cell cell6 = new Cell(new Phrase(jcsjLxxsglVO.getZymc(),contextBoldFont));
cell6.setHorizontalAlignment(Element.ALIGN_CENTER);
cell6.setVerticalAlignment(Element.ALIGN_CENTER);
cell6.setColspan(1);
cell6.setRowspan(1);
table1.addCell(cell6);
Cell cell7 = new Cell(new Phrase("学号",contextBoldFont));
cell7.setHorizontalAlignment(Element.ALIGN_CENTER);
cell7.setVerticalAlignment(Element.ALIGN_CENTER);
cell7.setColspan(1);
cell7.setRowspan(1);
table1.addCell(cell7);
Cell cell8 = new Cell(new Phrase(jcsjLxxsglVO.getXh(),contextBoldFont));
cell8.setHorizontalAlignment(Element.ALIGN_CENTER);
cell8.setVerticalAlignment(Element.ALIGN_CENTER);
cell8.setColspan(1);
cell8.setRowspan(1);
table1.addCell(cell8);
Cell cell9 = new Cell(new Phrase("学习形式",contextBoldFont));
cell9.setHorizontalAlignment(Element.ALIGN_CENTER);
cell9.setVerticalAlignment(Element.ALIGN_CENTER);
cell9.setColspan(1);
cell9.setRowspan(1);
table1.addCell(cell9);
Cell cell10= new Cell(new Phrase(jcsjLxxsglVO.getXxxsmc(),contextBoldFont));
cell10.setHorizontalAlignment(Element.ALIGN_CENTER);
cell10.setVerticalAlignment(Element.ALIGN_CENTER);
cell10.setColspan(1);
cell10.setRowspan(1);
table1.addCell(cell10);
Cell cell11 = new Cell(new Phrase("指导教师",contextBoldFont));
cell11.setHorizontalAlignment(Element.ALIGN_CENTER);
cell11.setVerticalAlignment(Element.ALIGN_CENTER);
cell11.setColspan(1);
cell11.setRowspan(1);
table1.addCell(cell11);
Cell cell12 = new Cell(new Phrase(jcsjLxxsglVO.getDsmc(),contextBoldFont));
cell12.setHorizontalAlignment(Element.ALIGN_CENTER);
cell12.setVerticalAlignment(Element.ALIGN_CENTER);
cell12.setColspan(1);
cell12.setRowspan(1);
table1.addCell(cell12);
Cell cell13 = new Cell(new Phrase("政治面貌",contextBoldFont));
cell13.setHorizontalAlignment(Element.ALIGN_CENTER);
cell13.setVerticalAlignment(Element.ALIGN_CENTER);
cell13.setColspan(1);
cell13.setRowspan(1);
table1.addCell(cell13);
Cell cell14 = new Cell(new Phrase(jcsjLxxsglVO.getZzmmmc(),contextBoldFont));
cell14.setHorizontalAlignment(Element.ALIGN_CENTER);
cell14.setVerticalAlignment(Element.ALIGN_CENTER);
cell14.setColspan(1);
cell14.setRowspan(1);
table1.addCell(cell14);
// Cell cell15 = new Cell(new Phrase("入党/团年月",contextBoldFont));
Cell cell15 = new Cell(new Phrase("地区",contextBoldFont));
cell15.setHorizontalAlignment(Element.ALIGN_CENTER);
cell15.setVerticalAlignment(Element.ALIGN_CENTER);
cell15.setColspan(1);
cell15.setRowspan(1);
table1.addCell(cell15);
// Cell cell16 = new Cell(new Phrase(jcsjLxxsglVO.getRdtsj(),contextBoldFont));
Cell cell16 = new Cell(new Phrase(jcsjLxxsglVO.getXq(),contextBoldFont));
cell16.setHorizontalAlignment(Element.ALIGN_CENTER);
cell16.setVerticalAlignment(Element.ALIGN_CENTER);
cell16.setColspan(1);
cell16.setRowspan(1);
table1.addCell(cell16);
Cell cell17 = new Cell(new Phrase("联系电话",contextBoldFont));
cell17.setHorizontalAlignment(Element.ALIGN_CENTER);
cell17.setVerticalAlignment(Element.ALIGN_CENTER);
cell17.setColspan(1);
cell17.setRowspan(1);
table1.addCell(cell17);
Cell cell18 = new Cell(new Phrase(jcsjLxxsglVO.getSjh(),contextBoldFont));
cell18.setHorizontalAlignment(Element.ALIGN_CENTER);
cell18.setVerticalAlignment(Element.ALIGN_CENTER);
cell18.setColspan(1);
cell18.setRowspan(1);
table1.addCell(cell18);
List<Cell> cell19 = new ArrayList<>();
if(CollectionUtils.isNotEmpty(jcsjLxxsglVO.getHjxxList()) && jcsjLxxsglVO.getHjxxList().size()>0 && !ObjectUtils.isEmpty(jcsjLxxsglVO.getHjxxList().get(0))){
int n = jcsjLxxsglVO.getHjxxList().size()-jcsjLxxsglVO.getHjxxList().size()%3+(jcsjLxxsglVO.getHjxxList().size()%3 == 0?0:3);
for(int i=0;i<n;i++){
if(i<jcsjLxxsglVO.getHjxxList().size()){
Cell cell20 = new Cell();
Chunk chunk0 = new Chunk((i+1)+"\n",contextBoldFont);
Chunk chunk1 = new Chunk(jcsjLxxsglVO.getHjxxList().get(i).getLinkName()+"\n",contextBoldFont1);
Chunk chunk2 = new Chunk((StringUtils.isNotEmpty(jcsjLxxsglVO.getHjxxList().get(i).getLinkDescribe())?jcsjLxxsglVO.getHjxxList().get(i).getLinkDescribe():"")+"\n",contextBoldFont0);
cell20.add(chunk0);
cell20.add(chunk1);
cell20.add(chunk2);
// 图标
Resource resource = new ClassPathResource(FILE_TEMPLATE_PATH);
InputStream is = resource.getInputStream();
byte[] fileByte = toByteArray(is);
Image image = Image.getInstance(fileByte); // 替换为图片路径
image.setAlignment(Image.ALIGN_RIGHT);
float desiredHeight = 50f; // 设置想要的图片高度为50用户单位
image.scaleToFit(desiredHeight, desiredHeight); // 按比例缩放图片
// image.setAbsolutePosition(500f,700f);
// image.setSpacingBefore(-10);
Chunk chunk3 = null;
if(StringUtils.equals(jcsjLxxsglVO.getHjxxList().get(i).getHandlingState(),"1")){
if("pdf".equals(exportType)){
chunk3 = new Chunk( " (已办理)" +"\n " ,
(StringUtils.equals(jcsjLxxsglVO.getHjxxList().get(i).getHandlingState(),"1")? zysxFontBlueBl : zysxFontBl));
cell20.add(chunk3);
}else {
// 转pdf时,这个图片转不了,会导致文档异常
Chunk chunk3_1 = new Chunk(" ", contextBoldFont);
chunk3 = new Chunk(image, desiredHeight, desiredHeight);
Chunk chunk3_2 = new Chunk(" " + "\n ", contextBoldFont);
cell20.add(chunk3_1);
cell20.add(chunk3);
cell20.add(chunk3_2);
}
}else{
chunk3 = new Chunk( " (未办理)" +"\n " ,
(StringUtils.equals(jcsjLxxsglVO.getHjxxList().get(i).getHandlingState(),"1")? zysxFontBlueBl : zysxFontBl));
/* Chunk chunk3 = new Chunk((StringUtils.equals(jcsjLxxsglVO.getHjxxList().get(i).getHandlingState(),"1")?" (已办理)":" (未办理)")+"\n" ,
(StringUtils.equals(jcsjLxxsglVO.getHjxxList().get(i).getHandlingState(),"1")? zysxFontBlueBl : zysxFontBl));
*/
cell20.add(chunk3);
}
Chunk chunk4 = new Chunk( " 签字/盖章"+"\n " ,zysxrqFont);
cell20.add(chunk4);
Chunk chunk5 = new Chunk( " 年 月 日",zysxrqFont);
cell20.add(chunk5);
cell19.add(i,cell20);
cell19.get(i).setHorizontalAlignment(Element.ALIGN_CENTER);
// cell19.get(i).setVerticalAlignment(Element.ALIGN_CENTER);
cell19.get(i).setColspan(2);
cell19.get(i).setRowspan(5);
table1.addCell(cell19.get(i));
}else {
cell19.add(i,new Cell());
cell19.get(i).setHorizontalAlignment(Element.ALIGN_CENTER);
// cell19.get(i).setVerticalAlignment(Element.ALIGN_CENTER);
cell19.get(i).setColspan(2);
cell19.get(i).setRowspan(5);
table1.addCell(cell19.get(i));
}
}
}
document.add(table1);
// List<String> footDetails = new ArrayList<>();
// footDetails.add("")
String footDetail = jcsjLxxsglVO.getLxdwbms();
if(StringUtils.isBlank(footDetail)){
// 默认这个话
footDetail = "1、离校手续办理时间段:6月24日至6月28日,办理完成后,可以领取毕业证、学位证。\n" +
"2、学费未交清的毕业生请及时缴纳学费。缴学费需通过支付宝(登录支付宝,定位到“杭州”,选择“政务”,选择“公共支付”,选择“按执收单位”,查询要素选择“学号”,输入学号,查询金额并完成缴费);\n" +
"3、如您有国家助学贷款,请及时联系银行还款,否则将产生不良信用记录;\n" +
"4、毕业生档案一般寄发至“就业报到证”左上方的抬头单位,请本人及时查询自己的档案到达情况;\n" +
"5、毕业生“户口迁移证”“就业报到证”可自取、同学代领或通过挂号信邮寄,请及时查收。" ;
}
jcsjLxxsglVO.setLxdwbms(footDetail);
Paragraph pt2 = new Paragraph(footDetail,contextBoldFont0);
// Paragraph pt2 = new Paragraph("1、离校手续办理时间段:6月24日至6月28日,办理完成后,可以领取毕业证、学位证。\n" +
// "2、学费未交清的毕业生请及时缴纳学费。缴学费需通过支付宝(登录支付宝,定位到“杭州”,选择“政务”,选择“公共支付”,选择“按执收单位”,查询要素选择“学号”,输入学号,查询金额并完成缴费);\n" +
// "3、如您有国家助学贷款,请及时联系银行还款,否则将产生不良信用记录;\n" +
// "4、毕业生档案一般寄发至“就业报到证”左上方的抬头单位,请本人及时查询自己的档案到达情况;\n" +
// "5、毕业生“户口迁移证”“就业报到证”可自取、同学代领或通过挂号信邮寄,请及时查收。",contextBoldFont0);
pt2.setAlignment(0);
pt2.setIndentationLeft(20);// 左缩进
pt2.setIndentationRight(20);// 右缩进
pt2.setLeading(10f);// 行间距
pt2.setSpacingBefore(5f);// 设置上空白
pt2.setSpacingAfter(5f);// 设置段落下空白
document.add(pt2);
}
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
}
工具类 word转pdf
点击查看代码
package com.ly.education.leaving.server.util;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.LineSeparator;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.apache.commons.lang.StringUtils.EMPTY;
/**
* itextpdf 表格工具类
*
* @Author: linjitai
* @Date: 2019/7/6 11:46
* @Author: update by linjitai on 20191017
*/
public class PdfUtil {
//成绩打印 add by ljt
private static final float borderWidth = 0.5f;//表格边框厚度
// BaseFont 中文字体
private static final BaseFont baseFont = createBaseFont();
// 标题字体
public static final Font titleFont = new Font(baseFont, 20, Font.NORMAL);
// 小标题
public static Font headFont = new Font(baseFont, 14, Font.BOLD);
// 正文字体
public static final Font normalFont = new Font(baseFont, 8, Font.NORMAL);
// 空行
public static final Paragraph blankRow = new Paragraph(10f, " ");
public static final Font FONT15 = new Font(baseFont, 15, Font.NORMAL);
public static final Font FONT14 = new Font(baseFont, 14, Font.NORMAL);
public static final Font FONT13 = new Font(baseFont, 13, Font.NORMAL);
public static final Font FONT12 = new Font(baseFont, 12, Font.NORMAL);
public static final Font FONT11 = new Font(baseFont, 11, Font.NORMAL);
public static final Font FONT10 = new Font(baseFont, 10, Font.NORMAL);
public static final Font FONT9 = new Font(baseFont, 9, Font.NORMAL);
public static final Font FONT8 = new Font(baseFont, 8, Font.NORMAL);
public static final Font FONT7 = new Font(baseFont, 7, Font.NORMAL);
public static final Font FONT6 = new Font(baseFont, 6, Font.NORMAL);
public static final Font FONT5 = new Font(baseFont, 5, Font.NORMAL);
// PDF最大宽度
private static int maxWidth = 520;
public static final String PDF_SUFFIX = ".pdf";
public static final String DOC_SUFFIX = ".doc";
public static final String DOCX_SUFFIX = ".docx";
/**
* 构造BaseFont 中文字体,静态工厂方法
*
* @return
*/
private static BaseFont createBaseFont() {
try {
return BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
return null;
}
public static PdfPCell getCell(Phrase phrase, int border) {
PdfPCell cell = new PdfPCell(phrase);
cell.setBorder(border);
return cell;
}
public static PdfPCell getCell(Phrase phrase, int horizontalAlignment, int verticalAlignment) {
PdfPCell cell = new PdfPCell(phrase);
cell.setHorizontalAlignment(horizontalAlignment);
cell.setVerticalAlignment(verticalAlignment);
return cell;
}
public static PdfPCell getCell(Phrase phrase, int border, int horizontalAlignment, int verticalAlignment) {
PdfPCell cell = new PdfPCell(phrase);
cell.setBorder(border);
cell.setHorizontalAlignment(horizontalAlignment);
cell.setVerticalAlignment(verticalAlignment);
return cell;
}
public static PdfPCell getNoBorderCell(Phrase phrase) {
PdfPCell cell = new PdfPCell(phrase);
cell.setBorder(PdfPCell.NO_BORDER);
return cell;
}
public static PdfPCell getAlignCenterCell(Phrase phrase) {
PdfPCell cell = new PdfPCell(phrase);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_CENTER);
return cell;
}
public static PdfPCell getNoBorderAndAlignCenterCell(Phrase phrase) {
PdfPCell cell = new PdfPCell(phrase);
cell.setBorder(PdfPCell.NO_BORDER);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_CENTER);
return cell;
}
/**
* 合并单元格并设值
*
* @param table
* @param rowIndex
* @param colIndex
* @param value
* @param font
* @param colspan
*/
public static void mergeCol(PdfPTable table, int rowIndex, int colIndex, String value, Font font, int colspan) {
PdfUtil.removeBorderWidth(table, rowIndex, colIndex, colspan - 1);
PdfUtil.setTableValueColSpan(table, rowIndex, colIndex, value, font, colspan);
}
/**
* 隐藏表格边框
*
* @param table
* @param rowIndex
* @param colIndex
*/
public static void removeBorderWidth(PdfPTable table, int rowIndex, int colIndex, int count) {
//上侧
for (int i = 1; i <= count; i++) {
setTableBorderWidthTop(table, rowIndex, i + colIndex);
}
//下侧
for (int i = 1; i <= count; i++) {
setTableBorderWidthBottom(table, rowIndex, i + colIndex);
}
//左侧
for (int i = 1; i <= count; i++) {
setTableBorderWidthLeft(table, rowIndex, i + colIndex);
}
//右侧
for (int i = 1; i <= count; i++) {
setTableBorderWidthRight(table, rowIndex, i + colIndex);
}
}
/**
* 指定单元格 横向合并 赋值
*
* @param table
* @param rowIndex
* @param colIndex
* @param value
* @param font
* @param colspan 合并单元格数目
*/
public static void setTableValueColSpan(PdfPTable table, int rowIndex, int colIndex, String value, Font font, int colspan) {
ArrayList rows = table.getRows();
PdfPRow row = (PdfPRow) rows.get(rowIndex);
PdfPCell[] cells = row.getCells();
PdfPCell cell = cells[colIndex];
Phrase newPhrase = Phrase.getInstance(2, value, font);
cell.setColspan(colspan);
cell.setBorderWidth(borderWidth);
cell.setPhrase(newPhrase);
}
/**
* 指定去除表格右侧线
*
* @param table
* @param rowIndex
* @param colIndex
*/
public static void setTableBorderWidthRight(PdfPTable table, int rowIndex, int colIndex) {
ArrayList rows = table.getRows();
PdfPRow row = (PdfPRow) rows.get(rowIndex);
PdfPCell[] cells = row.getCells();
PdfPCell cell = cells[colIndex];
cell.setBorderWidthRight(0);
}
/**
* 指定去除表格上侧线
*
* @param table
* @param rowIndex
* @param colIndex
*/
public static void setTableBorderWidthTop(PdfPTable table, int rowIndex, int colIndex) {
ArrayList rows = table.getRows();
PdfPRow row = (PdfPRow) rows.get(rowIndex);
PdfPCell[] cells = row.getCells();
PdfPCell cell = cells[colIndex];
cell.setBorderWidthTop(0);
}
/**
* 指定去除表格下侧线
*
* @param table
* @param rowIndex
* @param colIndex
*/
public static void setTableBorderWidthBottom(PdfPTable table, int rowIndex, int colIndex) {
ArrayList rows = table.getRows();
PdfPRow row = (PdfPRow) rows.get(rowIndex);
PdfPCell[] cells = row.getCells();
PdfPCell cell = cells[colIndex];
cell.setBorderWidthBottom(0);
}
/**
* 指定去除表格左侧线
*
* @param table
* @param rowIndex
* @param colIndex
*/
public static void setTableBorderWidthLeft(PdfPTable table, int rowIndex, int colIndex) {
ArrayList rows = table.getRows();
PdfPRow row = (PdfPRow) rows.get(rowIndex);
PdfPCell cell = row.getCells()[colIndex];
cell.setBorderWidthLeft(0);
}
/**
* 指定单元格赋值(定位到row与col),相当于坐标系(x,y);row为y轴,col为x轴
*
* @param table
* @param rowIndex
* @param colIndex
* @param value
* @param font
*/
public static void setTableValue(PdfPTable table, int rowIndex, int colIndex,
String value, Font font) {
PdfPCell cell = table.getRows().get(rowIndex).getCells()[colIndex];
Phrase newPhrase = Phrase.getInstance(2, value, font);
cell.setBorderWidth(borderWidth);
cell.setPhrase(newPhrase);
}
/**
* 填充表格
*
* @param table
* @param font
*/
public static void setAllTableValue(PdfPTable table, Font font) {
ArrayList rows = table.getRows();
for (int i = 1; i < rows.size(); i++) {
PdfPRow row = (PdfPRow) rows.get(i);
PdfPCell[] cells = row.getCells();
for (int j = 0; j < cells.length; j++) {
PdfPCell pdfPCell = cells[j];
Phrase phrase = pdfPCell.getPhrase();
Phrase newPhrase = Phrase.getInstance(2, "嘉佳" + i + j, font);
pdfPCell.setPhrase(newPhrase);
}
}
}
/**
* 生成一个表格并赋值
*
* @param value
* @param font
* @param align
* @return
*/
public static PdfPCell createCell(String value, Font font, int align) {
return getPdfPCell(value, font, align, borderWidth);
}
public static PdfPCell createCell(String value, Font font, int align, float borderWidth) {
return getPdfPCell(value, font, align, borderWidth);
}
private static PdfPCell getPdfPCell(String value, Font font, int align, float borderWidth) {
PdfPCell cell = new PdfPCell();
cell.setFixedHeight(Constant.FIXED_HEIGHT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setBorderWidth(borderWidth);
cell.setPhrase(new Phrase(value, font));
return cell;
}
public static PdfPCell createCell(String value, Font font, int align, float borderWidth, Integer fixedHeight) {
return getPdfPCell(value, font, align, borderWidth, fixedHeight);
}
private static PdfPCell getPdfPCell(String value, Font font, int align, float borderWidth, Integer fixedHeight) {
PdfPCell cell = new PdfPCell();
if (null != fixedHeight) {
cell.setFixedHeight(fixedHeight);
}
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setBorderWidth(borderWidth);
cell.setPhrase(new Phrase(value, font));
return cell;
}
public static void addPdfTextMark(String InPdfFile, String outPdfFile, String textMark, int textWidth,
int textHeight) throws Exception {
Document doc = null;
doc = new Document();
OutputStream outputStream = null;
PdfWriter writer = null;
writer = PdfWriter.getInstance(doc, outputStream);
PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));
PdfContentByte under;
BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", "Identity-H", true);// 使用系统字体
// 原pdf文件的总页数
int pageSize = reader.getNumberOfPages();
for (int i = 1; i <= pageSize; i++) {
// 水印在之前文本下
under = stamp.getUnderContent(i);
//水印在之前文本上
// under = stamp.getOverContent(i);
under.beginText();
// 文字水印 颜色
under.setColorFill(new BaseColor(211, 211, 211));
// 文字水印 字体及字号
under.setFontAndSize(font, 38);
// 文字水印 起始位置
under.setTextMatrix(textWidth, textHeight);
under.showTextAligned(Element.ALIGN_CENTER, textMark, textWidth, textHeight, 45);
under.endText();
}
// 关闭
stamp.close();
}
/**
* 添加文字水印
*
* @param pdfWriter
* @param alignment 对其方式 右侧对齐:Element.ALIGN_RIGHT,左侧对齐:Element.ALIGN_LEFT
* @param text 文本
* @param x x轴坐标(以对齐侧 为转轴进行旋转)
* @param y y轴坐标
* @param rotation 角度
*/
public static void setWaterMark(PdfWriter pdfWriter, final int alignment, final String text, final float x, final float y, final float rotation) {
// 加入水印
PdfContentByte waterMar = pdfWriter.getDirectContentUnder();
// 开始设置水印
waterMar.beginText();
// 设置水印透明度
PdfGState gs = new PdfGState();
// 设置填充字体不透明度为0.4f
gs.setFillOpacity(Constant.WATER_MARK_PDF_OPACITY);
try {
// 设置水印字体参数及大小(字体参数,字体编码格式,是否将字体信息嵌入到pdf中(一般不需要嵌入),字体大小)
//支持中文
BaseFont baseChina = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// BaseFont base = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
waterMar.setFontAndSize(baseChina, Constant.WATER_MARK_PDF_SIZE);
// 设置透明度
waterMar.setGState(gs);
// 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
waterMar.showTextAligned(alignment, text, x, y, rotation);
// 设置水印颜色
waterMar.setColorFill(BaseColor.GRAY);
//结束设置
waterMar.endText();
waterMar.stroke();
} catch (IOException | DocumentException e) {
e.printStackTrace();
} finally {
waterMar = null;
gs = null;
}
}
/**
* 设置图片水印
*
* @param pdfWriter
* @param imagePath
* @throws DocumentException
*/
public static void setWaterMarkPic(PdfWriter pdfWriter, String imagePath) throws DocumentException {
// 加入水印
PdfContentByte waterMar = pdfWriter.getDirectContentUnder();
// 开始设置水印
waterMar.beginText();
// 设置水印透明度
PdfGState gs = new PdfGState();
// 设置笔触字体不透明度为0.4f
gs.setStrokeOpacity(0.4f);
try {
Image image = Image.getInstance(imagePath);
// 设置坐标 绝对位置 X Y
image.setAbsolutePosition(200, 300);
// 设置旋转弧度
image.setRotation(30);// 旋转 弧度
// 设置旋转角度
image.setRotationDegrees(45);// 旋转 角度
// 设置等比缩放
image.scalePercent(90);// 依照比例缩放
// image.scaleAbsolute(200,100);//自定义大小
// 设置透明度
waterMar.setGState(gs);
// 添加水印图片
waterMar.addImage(image);
// 设置透明度
waterMar.setGState(gs);
//结束设置
waterMar.endText();
waterMar.stroke();
} catch (IOException e) {
e.printStackTrace();
} finally {
waterMar = null;
gs = null;
}
}
/**
* 创建一个剧中对其的格子并赋值(有线框)
*
* @param info
* @param font
* @param horizontalAlignment 水平位置居上下左右
* @param verticalAlignment 垂直位置居上下左右
*/
public static PdfPCell setCell(String info, Font font,Integer horizontalAlignment,Integer verticalAlignment) {
PdfPCell cell = new PdfPCell(new Phrase(info, font));
cell.setPaddingTop(4.0f);
cell.setPaddingBottom(4.0f);
if(null == horizontalAlignment){
horizontalAlignment = Element.ALIGN_CENTER;
}
cell.setHorizontalAlignment(horizontalAlignment);
if(null == verticalAlignment){
verticalAlignment = Element.ALIGN_MIDDLE;
}
cell.setVerticalAlignment(verticalAlignment);
// cell.setFixedHeight(Constant.FIXED_HEIGHT);
return cell;
}
public static PdfPCell setCell(String info, Font font,Integer horizontalAlignment,Integer verticalAlignment,Integer Height) {
PdfPCell cell = new PdfPCell(new Phrase(info, font));
cell.setPaddingTop(4.0f);
cell.setPaddingBottom(4.0f);
cell.setMinimumHeight(Height);
if(null == horizontalAlignment){
horizontalAlignment = Element.ALIGN_CENTER;
}
cell.setHorizontalAlignment(horizontalAlignment);
if(null == verticalAlignment){
verticalAlignment = Element.ALIGN_MIDDLE;
}
cell.setVerticalAlignment(verticalAlignment);
// cell.setFixedHeight(Constant.FIXED_HEIGHT);
return cell;
}
/**
* 创建一个居中对其的格子并赋值(无线框)
*
* @param info
* @param font
* @return
*/
public static PdfPCell setCellNoBorder(String info, Font font) {
Phrase phrase = new Phrase(info, font);
// 下划线
if(StringUtils.isNotBlank(info)){
int percentage = info.length()>7 ? 65:50;
LineSeparator underline = new LineSeparator(1, percentage, BaseColor.GRAY, Element.ALIGN_LEFT, -2);
phrase.add(underline);
}
PdfPCell cell = new PdfPCell(phrase);
cell.setPaddingTop(7.0f);
cell.setPaddingBottom(7.0f);
// cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
// cell.setFixedHeight(Constant.FIXED_HEIGHT);
cell.setBorder(PdfPCell.NO_BORDER);
return cell;
}
/**
* withs 与 infos 长度必须想等,不然得不到正确的结果
* 表格循环遍历插入cell(无边框)
*
* @param withs
* @param infos
* @param font
* @return
* @throws DocumentException
*/
public static PdfPTable fillTableNoBorder(float[] withs, String[] infos, Font font) throws DocumentException {
PdfPTable table = new PdfPTable(withs.length);
table.setWidths(withs);
for (int i = 0; i < infos.length; i++) {
table.addCell(setCellNoBorder(infos[i], font));
}
table.setWidthPercentage(Constant.WIDTH);
return table;
}
/**
* withs 与 infos 长度必须想等,不然得不到正确的结果
* 表格循环遍历插入cell(有边框)
*
* @param withs
* @param infos
* @param font
* @param horizontalAlignments 水平位置
* @param verticalAlignments 垂直位置
* @return
* @throws DocumentException
*/
public static PdfPTable fillTable(float[] withs, String[] infos, Font font, Integer[] horizontalAlignments, Integer[] verticalAlignments) throws DocumentException {
PdfPTable table = new PdfPTable(withs.length);
table.setWidths(withs);
for (int i = 0; i < infos.length; i++) {
table.addCell(setCell(infos[i], font,horizontalAlignments[i],verticalAlignments[i]));
}
table.setWidthPercentage(Constant.WIDTH);
return table;
}
//可以设置Cell高度
public static PdfPTable fillTable(float[] withs, String[] infos, Font font, Integer[] horizontalAlignments, Integer[] verticalAlignments,Integer cellHeight) throws DocumentException {
PdfPTable table = new PdfPTable(withs.length);
table.setWidths(withs);
for (int i = 0; i < infos.length; i++) {
table.addCell(setCell(infos[i], font,horizontalAlignments[i],verticalAlignments[i],cellHeight));
}
table.setWidthPercentage(Constant.WIDTH);
return table;
}
/**
* withs 与 infos 长度必须想等,不然得不到正确的结果
* 嵌套表格(无边框)循环遍历插入cell
*
* @param withs
* @param infos
* @param font
* @param horizontalAlignments 水平位置
* @param verticalAlignments 垂直位置
* @return
* @throws DocumentException
*/
public static PdfPCell fillInsideTable(float[] withs, String[] infos, Font font, Integer[] horizontalAlignments, Integer[] verticalAlignments) throws DocumentException {
PdfPTable table = new PdfPTable(withs.length);
table.setWidths(withs);
for (int i = 0; i < infos.length; i++) {
table.addCell(setCell(infos[i], font,horizontalAlignments[i],verticalAlignments[i]));
}
PdfPCell cell = new PdfPCell(table);
cell.setBorder(PdfPCell.NO_BORDER);
return cell;
}
/**
* word to pdf and compress to zip
* 配合使用 freeMarker
* 部分字符会丢失,比如
标签:word,ALIGN,param,离校,static,new,pdf,Font,public
From: https://www.cnblogs.com/heavenTang/p/18222090