添加maven依赖
这个连接
通过 Maven 仓库安装 Spire 系列 Java 产品
import com.spire.pdf.PdfDocument;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
public class HeaderFooterUtils {
public static void main(String[] args) {
//创建pdfDocument对象,并加载PDF文档
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\long\\Desktop\\ceshi.pdf");
//删除有红色字体的一页: Evaluation Warning : The document was created with Spire.PDF for Java.
doc.getPages().add();
doc.getPages().remove(doc.getPages().get(doc.getPages().getCount() - 1));
//添加页眉
//drawHeader(doc);
//添加页脚
drawFooter(doc);
//保存文档
doc.saveToFile("C:\\Users\\long\\Desktop\\result.pdf");
}
//添加页眉
public static void drawHeader(PdfDocument doc) {
//获取页面尺寸
Dimension2D pageSize = doc.getPages().get(0).getSize();
//定义两个float变量
float x = 90;
float y = 20;
for (int i = 0; i < doc.getPages().getCount(); i++) {
//添加图片到指定位置
PdfImage headerImage = PdfImage.fromFile("C:\\Users\\long\\Desktop\\logo.png");
float width = headerImage.getWidth() / 2;
float height = headerImage.getHeight() / 2;
doc.getPages().get(i).getCanvas().drawImage(headerImage, x, y, width, height);
//添加横线至图片下
PdfPen pen = new PdfPen(PdfBrushes.getGray(), 0.5f);
doc.getPages().get(i).getCanvas().drawLine(pen, x, y + height + 1, pageSize.getWidth() - x, y + height + 1);
}
}
//添加页脚
public static void drawFooter(PdfDocument doc) {
//获取页面大小
Dimension2D pageSize = doc.getPages().get(0).getSize();
//定义两个float变量
float x = 90;
float y = (float) pageSize.getHeight() - 72;
for (int i = 0; i < doc.getPages().getCount(); i++) {
//添加横线到指定位置
PdfPen pen = new PdfPen(PdfBrushes.getGray(), 0.5f);
doc.getPages().get(i).getCanvas().drawLine(pen, x, y, pageSize.getWidth() - x, y);
//添加文本到页脚处
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("黑体", Font.PLAIN, 8), true);//
//PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
//String footerText = "这里可以在页脚添加自己想要添加的内容";
//doc.getPages().get(i).getCanvas().drawString(footerText, font, PdfBrushes.getBlack(), x, y, format);
//添加页码
PdfPageNumberField number = new PdfPageNumberField();
PdfPageCountField count = new PdfPageCountField();
PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.getBlack(), "第{0}页 共{1}页", number, count);
compositeField.setStringFormat(new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top));
Dimension2D fontSize = font.measureString(compositeField.getText());
compositeField.setBounds(new Rectangle2D.Float((float) (pageSize.getWidth() - x - fontSize.getWidth()), y, (float) fontSize.getWidth(), (float) fontSize.getHeight()));
compositeField.draw(doc.getPages().get(i).getCanvas());
}
}
}
只是这个执行效率极低,提供一个思路去解决这个问题,就是利用多线程,分页处理(比如定义一个页码节点,满足多少页就开一个线程来处理)
请参考我另一篇博客