前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用 openPDF 创建带目录的文档时候, 使用如下方式, 可以保证目录页码准确

使用 openPDF 创建带目录的文档时候, 使用如下方式, 可以保证目录页码准确

作者头像
北漂的我
发布2022-12-28 14:47:30
8420
发布2022-12-28 14:47:30
举报
文章被收录于专栏:北漂的我
代码语言:javascript
复制
public static void main(String[] args) throws Exception {
	pdfboxTest5();
}

代码语言:javascript
复制
private static void pdfboxTest5() throws DocumentException, IOException {
	File file = new File("E:\\sss\\test5.pdf");
	Document doc = new Document(PageSize.A4);
	String tempFileName = "." + File.separator + UUID.randomUUID().toString() + ".pdf";
	PdfWriter pdfWriter = PdfWriter.getInstance(doc, new FileOutputStream(new File(tempFileName)));
	ContentEvent contentEvent = new ContentEvent();
	pdfWriter.setPageEvent(contentEvent);
	List<Chapter> chapterList = new ArrayList<>();
	HeaderFooter header = new HeaderFooter(false, new Phrase("测试页眉", getFont(100)));
	header.setBorder(Rectangle.BOTTOM);
	header.setAlignment(Element.ALIGN_CENTER);
	HeaderFooter footer = new HeaderFooter(new Phrase("第", getFont(100)), new Phrase("页", getFont(100)));
	footer.setBorder(Rectangle.TOP);
	footer.setAlignment(Element.ALIGN_CENTER);
	doc.setHeader(header);
	doc.setFooter(footer);

	doc.open();
	for (int i = 0; i < 10; i++) {
		Chapter chapter = new Chapter(new Paragraph("第" + (i + 1) + "单元", getFont(1)), i + 1);
		chapter.setTriggerNewPage(false);
//		chapter.setIndentation(10);
		for (int j = 0; j < 5; j++) {
			Section section = chapter.addSection(10, new Paragraph("第" + (j + 1) + "节", getFont(2)));
			for (int k = 0; k < 3; k++) {
				Section subSection = section.addSection(10, new Paragraph("第" + (k + 1) + "题", getFont(3)));
				subSection.add(new Paragraph("测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测测试测试", getFont(100)));
			}
		}
		chapterList.add(chapter);
		doc.add(chapter);
	}
	doc.close();

	PdfReader reader = new PdfReader(tempFileName);
	int numberOfPages = reader.getNumberOfPages();
	PdfTextExtractor pdfTextExtractor = new PdfTextExtractor(reader);
	Map<String, Integer> muluTempMap = new LinkedHashMap<>();
	for (int i = 0; i < numberOfPages; i++) {
		String textFromPage = pdfTextExtractor.getTextFromPage(i + 1);
		String[] texts = Arrays.stream(textFromPage.split("\n")).map(string -> string.trim()).filter(string -> string.trim().indexOf(".") >= 1 && string.trim().contains(". ")).toArray(String[]::new);
		for (String string : texts) {
			muluTempMap.put(string.trim(), i + 1);
		}
	}
	new File(tempFileName).delete();

	Document document = new Document(PageSize.A4);
	PdfWriter.getInstance(document, new FileOutputStream(file));
	document.open();
	Paragraph mulu = new Paragraph("目录", getFont(1));
	mulu.setSpacingAfter(10);
	Chapter indexChapter = new Chapter(mulu, 0);
	indexChapter.setNumberDepth(0);
	for (Entry<String, Integer> entry : contentEvent.index.entrySet()) {
		String title = entry.getKey();
		String titleSub = title.substring(0, title.indexOf(". ") + 1);
		String titleTemp = titleSub.replaceAll("\\.", "");
		Paragraph paragraph = new Paragraph(title, getFont(titleSub.length() - titleTemp.length() + 10));
		paragraph.setIndentationLeft((titleSub.length() - titleTemp.length() - 1) * 10);
		paragraph.add(new Chunk(new DottedLineSeparator()));
		paragraph.add(new Chunk(String.valueOf(muluTempMap.get(entry.getKey())), getFont(100)));
		indexChapter.add(paragraph);
	}

	document.add(indexChapter);
	document.setHeader(header);
	document.setFooter(footer);
	document.resetPageCount();
	document.newPage();
	for (Chapter chapter : chapterList) {
		document.add(chapter);
	}
	document.close();
}
代码语言:javascript
复制
private static class ContentEvent extends PdfPageEventHelper {
	Map<String, Integer> index = new LinkedHashMap<>();

	@Override
	public void onChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) {
		index.put(title.getContent().trim(), 0);
	}

	@Override
	public void onSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title) {
		index.put(title.getContent().trim(), 0);
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-12-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档