1、配置
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.11</version>
<type>pom</type>
</dependency>
2.生成pdf
PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false); //处理中文问题
PdfWriter writer = new PdfWriter(new FileOutputStream(new File(filePath)));
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
Paragraph p =new Paragraph("hello word!我创建的第一个pdf文件");
p.setFont(font);
p.setFontSize(12);
p.setBorder(new SolidBorder(Color.RED,0.5f));//边框
p.setBackgroundColor(Color.GREEN);//绿色你懂的
document.add(p);
document.close();
writer.close();
pdf.close();/**
3、页码
/**
* @author QiaoFengTao
* @Title:
* @Description: 生成页码辅助类
* @date 2021/7/5 15:54
*/
public class TextFooterEventHandler implements IEventHandler {
private Document document;
private PdfFont font;
public TextFooterEventHandler(Document document, PdfFont font){
this.document = document;
this.font = font;
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent pdfEvent = (PdfDocumentEvent) event;
PdfPage page = pdfEvent.getPage();
PdfDocument pdfDoc = pdfEvent.getDocument();
//获取当前页码
int pageNumber = pdfDoc.getPageNumber(page);
PdfCanvas pdfCanvas = new PdfCanvas(page);
PageSize pageSize = pdfDoc.getDefaultPageSize();
pdfCanvas.beginText()
.setFontAndSize(this.font, 12)
.moveText(pageSize.getWidth() / 2 - 30, 20)
.showText("- 第 " + pageNumber + " 页 -")
.endText()
.release();
}
}
4、页眉页脚
/**
* 页眉页脚
* @author QiaoFengTao
* @date 2021/7/15 18:41
*/
public class HeaderFooterHandler implements IEventHandler {
private PdfFont font;
public HeaderFooterHandler(PdfFont font) {
this.font = font;
}
@Override
public void handleEvent( Event event) {
try {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdfDoc = docEvent.getDocument();
Document doc = new Document(pdfDoc);
PdfPage page = docEvent.getPage();
Rectangle pageSize = page.getPageSize();
float pdfWidth = pageSize.getWidth();
float pdfHeight = pageSize.getHeight();
PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
float tableWidth = pdfWidth - doc.getRightMargin() - doc.getLeftMargin();
// 页眉
float x0 = doc.getRightMargin(), y0 = pdfHeight - doc.getTopMargin() - 20;
pdfCanvas.moveTo(x0, y0);
Paragraph pageNameParagraph = new Paragraph();
pageNameParagraph.setVerticalAlignment(VerticalAlignment.BOTTOM);
pageNameParagraph.add(getLogoImage());
pageNameParagraph.setTextAlignment(TextAlignment.RIGHT);
pageNameParagraph.setFixedPosition(x0, y0, tableWidth);
doc.add(pageNameParagraph);
} catch (final Exception e) {
e.printStackTrace();
}
}
/*
* 页眉logo
**/
private Image getLogoImage() {
ClassPathResource resources = new ClassPathResource("\\static\\image\\header_logo.png");
Image headerImg = null;
try {
headerImg = new Image(ImageDataFactory.create(resources.getURI().toString()));
} catch (IOException e) {
e.printStackTrace();
}
headerImg.scaleToFit(120, 150);
return headerImg;
}
}
5、添加背景图
/**
* @author QiaoFengTao
* @date 2021/7/19 18:02
*/
public class BackgroundEventHandler implements IEventHandler {
public BackgroundEventHandler() {
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdfDoc = docEvent.getDocument();
PdfPage page = docEvent.getPage();
Rectangle pageSize = page.getPageSize();
float pdfWidth = pageSize.getWidth();
ClassPathResource resources = new ClassPathResource("\\static\\image\\pdf_bk.jpg");
ImageData images = null;
try {
images = ImageDataFactory.create(resources.getURI().toString());
images.setWidth(pdfWidth);
} catch (IOException e) {
e.printStackTrace();
}
PdfCanvas canvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
canvas.addImage(images,0,0,true);
}
}
6、替换pdf模板中文本内容
1、先获取占位符的位置信息;
/**
* 获取替换值位置信息
* @Author qiaofengtao
* @Date 2021/7/20 11:46
**/
public List<QuitReportPdfCoverVO> getKeyPosition(Map<String,String> keyMap,String sourcePath,String finishPath){
List<QuitReportPdfCoverVO> coverVOList = new ArrayList<>();
PdfDocument pdfDocument = null;
try {
pdfDocument = new PdfDocument(new PdfReader(sourcePath), new PdfWriter(finishPath));
for (String key : keyMap.keySet()) {
PdfPage page = pdfDocument.getFirstPage();
RegexBasedLocationExtractionStrategy strategy = new RegexBasedLocationExtractionStrategy(key);
PdfCanvasProcessor canvasProcessor = new PdfCanvasProcessor(strategy);
canvasProcessor.processPageContent(page);
Collection<IPdfTextLocation> resultantLocations = strategy.getResultantLocations();
for (IPdfTextLocation location : resultantLocations) {
Rectangle rectangle = location.getRectangle();
QuitReportPdfCoverVO quitReportPdfCoverVO = new QuitReportPdfCoverVO();
quitReportPdfCoverVO.setWidth(rectangle.getWidth());
quitReportPdfCoverVO.setHeight(rectangle.getHeight());
quitReportPdfCoverVO.setCoordinateX(rectangle.getX());
quitReportPdfCoverVO.setCoordinateY(rectangle.getY());
quitReportPdfCoverVO.setKey(key);
quitReportPdfCoverVO.setValue(keyMap.get(key));
coverVOList.add(quitReportPdfCoverVO);
}
}
} catch (IOException e) {
log.error("==========pdf封面获取替换值的坐标位置错误:", e);
throw new BusinessException(EmBusinessError.UNKNOWN_ERROR);
} finally {
pdfDocument.close();
}
return coverVOList;
}
2、替换该位置的内容。
/**
* 替换
* @Author qiaofengtao
* @Date 2021/7/20 11:46
**/
public void replaceKey(String orgName,String sourcePath,String finishPath,List<QuitReportPdfCoverVO> coverVOList){
PdfDocument pdfDoc = null;
try {
pdfDoc = new PdfDocument(new PdfReader(sourcePath), new PdfWriter(finishPath));
PdfCanvas canvas = new PdfCanvas(pdfDoc.getFirstPage().newContentStreamAfter(), pdfDoc.getFirstPage().getResources(), pdfDoc);
canvas.saveState();
//覆盖原本的字体
for (QuitReportPdfCoverVO coverVO : coverVOList) {
canvas.setFillColor(ColorConstants.WHITE);
canvas.rectangle(coverVO.getCoordinateX(), coverVO.getCoordinateY(), coverVO.getWidth(), coverVO.getHeight());
}
canvas.fill();
canvas.restoreState();
//填充新内容
canvas.beginText();
//pdf_font字体包位置
PathsProperties pathsProperties = myProperties.getPathsProperties();
String pdfFontPath = myProperties.getPathsProperties().getUploadBaseDir().concat(pathsProperties.getPdfFont());
PdfFont baseFont = PdfFontFactory.createFont(pdfFontPath.concat("HKYTW9.TTF"), PdfEncodings.IDENTITY_H,true);
PdfFont baseFont2 = PdfFontFactory.createFont(pdfFontPath.concat("HKYTW7.TTF"), PdfEncodings.IDENTITY_H,true);
canvas.setFontAndSize(baseFont2, coverVO.getHeight());
canvas.setTextMatrix(coverVO.getCoordinateX(), coverVO.getCoordinateY());
canvas.setColor(ColorConstants.BLACK,true);
canvas.newlineShowText(3,2,coverVO.getValue());
}
canvas.endText();
} catch (IOException e) {
log.error("==========pdf封面替换原来内容错误:", e);
throw new BusinessException(EmBusinessError.UNKNOWN_ERROR);
} finally {
pdfDoc.close();
}
}
若有不足
请移步 itext7 开发文档