一、效果图
1.带页码效果
2.目录效果
前言:Java 使用iText7生成带页码的PDF文件,同时生成目录PDF,但限于水平,暂时还在摸索合并两个PDF。不过看了一下,iText好像有生成目录的代码,可以查看我另一篇博客我copy了一份说明QAQ。
点击这里可下载源码
二、实现代码
1.PDFUtil.java(添加标题、锻炼辅助类)
package test.hui;import java.io.IOException;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;import com.itextpdf.io.font.PdfEncodings;import com.itextpdf.io.image.ImageData;import com.itextpdf.io.image.ImageDataFactory;import com.itextpdf.kernel.events.IEventHandler;import com.itextpdf.kernel.events.PdfDocumentEvent;import com.itextpdf.kernel.font.PdfFont;import com.itextpdf.kernel.font.PdfFontFactory;import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.kernel.pdf.PdfWriter;import com.itextpdf.kernel.pdf.xobject.PdfImageXObject;import com.itextpdf.layout.Document;import com.itextpdf.layout.element.AreaBreak;import com.itextpdf.layout.element.Image;import com.itextpdf.layout.element.Paragraph;import com.itextpdf.layout.property.TextAlignment;/*** * * * * @author Hui**/public class PDFUtil {public static String DEST2 = "";//文件路径 public static PdfFont sysFont =null;private Map<String, Integer> catalogMap = new LinkedHashMap<String, Integer>();//<标题,页数>public PDFUtil(String url){try {//sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);//中文设置 sysFont = PdfFontFactory.createFont("c://windows//fonts//simsun.ttc,1",PdfEncodings.IDENTITY_H, false);//中文设置,解决特殊字符错误DEST2=url;} catch (IOException e) {e.printStackTrace();}}/*** 创建pdf doc* @return doc* */public Document createPdfDoc() throws Exception{ PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST2)); Document doc = new Document(pdfDoc);//构建文档对象 //设置页码TextFooterEventHandler eh= new TextFooterEventHandler(doc);pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE,eh);return doc;}/*** 添加大标题* @param* * */public void addTitle(Document doc,String title) throws Exception{ Paragraph paragraph = new Paragraph(); paragraph.add(title).setFont(sysFont).setBold().setFontSize(20).setTextAlignment(TextAlignment.CENTER);doc.add(paragraph);}/*** 添加一级标题* @param* * */public void addHeading1(Document doc,String pg) throws Exception{Paragraph paragraph = new Paragraph(); paragraph.add(pg).setFont(sysFont).setBold().setFontSize(16); doc.add(paragraph);catalogMap.put(pg, doc.getPdfDocument().getNumberOfPages());}/*** 添加二级标题* @param* * */public void addHeading2(Document doc,String pg) throws Exception{Paragraph paragraph = new Paragraph(); paragraph.add(pg).setFont(sysFont).setBold().setFontSize(14).setFirstLineIndent(14); doc.add(paragraph);catalogMap.put(pg, doc.getPdfDocument().getNumberOfPages());}/*** 添加三级标题* @param* * */public void addHeading3(Document doc,String pg) throws Exception{Paragraph paragraph = new Paragraph(); paragraph.add(pg).setFont(sysFont).setBold().setFontSize(12); doc.add(paragraph);catalogMap.put(pg, doc.getPdfDocument().getNumberOfPages());}/*** 添加段落* @param* */public void addParagraph(Document doc,String pg) throws Exception{Paragraph paragraph = new Paragraph(); paragraph.add(pg).setFont(sysFont).setFirstLineIndent(20);//中文字体,首行缩进doc.add(paragraph);}/*** 添加图片* @param* */public void addImg(Document doc,String url) throws Exception{ImageData imgData=ImageDataFactory.create(url);Image pic=new Image(imgData);doc.add(pic);}public Map<String, Integer> getCatalogMap() {return catalogMap;}public void setCatalogMap(Map<String, Integer> catalogMap) {this.catalogMap = catalogMap;}}
2.TextFooterEventHandler.java(生成页码辅助类)
package test.hui;import java.io.IOException;import com.itextpdf.io.font.FontConstants;import com.itextpdf.kernel.events.Event;import com.itextpdf.kernel.events.IEventHandler;import com.itextpdf.kernel.events.PdfDocumentEvent;import com.itextpdf.kernel.font.PdfFontFactory;import com.itextpdf.kernel.geom.Rectangle;import com.itextpdf.kernel.pdf.canvas.PdfCanvas;import com.itextpdf.layout.Document;/*** * * * * @author Hui* **/public class TextFooterEventHandler implements IEventHandler {protected Document doc;protected int page;public TextFooterEventHandler(Document doc) {this.doc = doc;}@Overridepublic void handleEvent(Event event) {PdfDocumentEvent docEvent = (PdfDocumentEvent) event;PdfCanvas canvas = new PdfCanvas(docEvent.getPage());Rectangle pageSize = docEvent.getPage().getPageSize(); page++;canvas.beginText();try {canvas.setFontAndSize(PdfFontFactory.createFont(FontConstants.HELVETICA_OBLIQUE), 15);} catch (IOException e) {e.printStackTrace();}canvas.moveText((pageSize.getRight() - doc.getRightMargin() + (pageSize.getLeft() + doc.getLeftMargin())) / 2,pageSize.getBottom() + doc.getBottomMargin()).showText(""+page).endText().release();}}
3.Testp.java
package test.hui;import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import com.itextpdf.kernel.events.PdfDocumentEvent;import com.itextpdf.kernel.pdf.PdfDocument;import com.itextpdf.layout.Document;public class Testp{public static String url="G:\\test4.pdf";//这里两个路径应改成你自己的路径public static String urlOrig="G:\\test1.pdf";static Map<String, Integer> catalogMap = new HashMap<String, Integer>();public static void main(String[] args) throws Exception { long old = System.currentTimeMillis();//生成内容pdfPDFUtil pdfUtil=new PDFUtil(url);Document doc=pdfUtil.createPdfDoc();PdfDocument pdfDoc=doc.getPdfDocument();//这里生成页码,引用TextFooterEventHandler的方法TextFooterEventHandler eh= new TextFooterEventHandler(doc);pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE,eh);pdfUtil.addTitle(doc, "预案");for(int i=0;i<15;i++){pdfUtil.addHeading1(doc,i+" 标题");if(i%2==0){pdfUtil.addHeading2(doc,i+".1 小标题标题");}pdfUtil.addParagraph(doc, "内容QAQAQZAAAWQSXFDSFSD内容QAQAQZAAAWQSXFDSFSD内容QAQAQZAAAWQSXFDSFSD内容QAQAQZAAAWQSXFDSFSD内容QAQAQZAAAWQSXFDSFSD");}pdfDoc.close(); doc.close();//------------------分割线-------------- //生成目录方法,暂时只能生产目录的pdf,还需努力合并PDFUtil pdfUtil2=new PDFUtil(urlOrig);Document doc2=pdfUtil2.createPdfDoc();System.out.println(doc2.getPdfDocument().getCatalog().getPdfObject());for(Entry<String, Integer> entry:pdfUtil.getCatalogMap().entrySet()){String title=entry.getKey();String page=entry.getValue()+""; if(countInString(title, ".")==0){pdfUtil2.addParagraph(doc2, title+"......."+page);}else if(countInString(title, ".")==1){pdfUtil2.addParagraph(doc2, title+"......."+page);}else{} }doc2.close();long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:"+url+","+urlOrig);} //用来控制生成目录public static int countInString(String str1, String str2) {int total = 0;for (String tmp = str1; tmp != null && tmp.length() >= str2.length();){if(tmp.indexOf(str2) == 0){total++;tmp = tmp.substring(str2.length());}else{tmp = tmp.substring(1);}}return total;}}
如果觉得《Java 使用iText7生成带页码的PDF文件(同时生成目录 但是不会合并两个PDF)》对你有帮助,请点赞、收藏,并留下你的观点哦!