页眉和页脚一般是显示文档的附加信息,经常使用来插入页码、时间、日期、我的信息、微标等。特别是其中插入的页码,经过这种方式可以快速定位所要查找的页面。本文将经过使用Java程序来演示如何在PDF文档中添加页眉页脚。
Spire.PDF没有提供直接添加页眉页脚到PDF的方法。为了实现此功能,我首先建立了drawHeader和drawFooter方法。如下代码适用于大部分Word转换成的PDF文档,其页边距默认值为上/下72磅,左/右90磅。因此若文档页边距有所差别,可经过调整下文代码中“X”“Y”值来获取最佳效果。html
方法1:经过官网下载获取jar包。解压后将lib文件夹下的Spire.Pdf.jar文件导入Java程序。(以下图)java
方法2:经过maven仓库安装导入。具体安装教程详见此网页。maven
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 HeaderFooter { public static void main(String[] args) { //建立pdfDocument对象,并加载PDF文档 PdfDocument doc = new PdfDocument(); doc.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.pdf"); //添加页眉 drawHeader(doc); //添加页脚 drawFooter(doc); //保存文档 doc.saveToFile("output/添加页眉页脚.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\\Test\\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); //添加文本到指定位置 y = y + 8; PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,8),true); PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left); String footerText = "姓名:Lily\n联系电话:0101112222\n网站:www.Lilyhome.com"; 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()); } } }
(本文完)工具