本文主要是介绍使用itextpdf对PDF文件添加页码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原本想着谷歌后用下CV大法,无奈找不到合适的,刚好手头有一些代码,就拿来改了改,这样反而更快。说是对PDF添加页码,其实就是将页码印到PDF上,下面的这种方法比较灵活也比较简单,可以对添加页码的内容以及位置进行调整。话不多说,直接上代码。
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;public class PDFUtil{// 必须要有private static final String PATH_FONT_COUR = "C:\\Windows\\Fonts\\STFANGSO.TTF";public static void addPageNum(String pdfPath, String outFilePath) {PdfReader reader = null;PdfStamper stamper = null;try {// 创建一个pdf读入流reader = new PdfReader(pdfPath);// 根据一个pdfreader创建一个pdfStamper.用来生成新的pdf.stamper = new PdfStamper(reader, new FileOutputStream(outFilePath));// 这个字体是itext-asian.jar中自带的 所以不用考虑操作系统环境问题.BaseFont bf = BaseFont.createFont(PATH_FONT_COUR, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);// baseFont不支持字体样式设定.但是font字体要求操作系统支持此字体会带来移植问题.Font font = new Font(bf, 10);font.setStyle(Font.BOLD);font.getBaseFont();// 获得宽Rectangle pageSize = reader.getPageSize(1);float width = pageSize.getWidth();// 获取页码int num = reader.getNumberOfPages();for (int i = 1; i <= num; i++) {PdfContentByte over = stamper.getOverContent(i);over.beginText();over.setFontAndSize(font.getBaseFont(), 13);over.setColorFill(BaseColor.BLACK);// 设置页码在页面中的坐标over.setTextMatrix((int) width - 55, 15);
// over.setTextRenderingMode(1); // 设置字体加粗over.showText("第" + i + "页");over.endText();over.stroke();}stamper.close();} catch (Exception e) {e.printStackTrace();} finally {if (reader != null) {reader.close();}}}
}
可以把获取高和宽的代码放到for循环里面,这样获取的高宽为每页的高和宽(有的PDF文件每页的高宽不一致),这样添加水印就不会出现水印添加不上的情况。
这篇关于使用itextpdf对PDF文件添加页码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!