PDFBOX 添加书签和合并多个pdf

pom 引入

		<dependency>
			<groupId>org.apache.pdfbox</groupId>
			<artifactId>pdfbox</artifactId>
			<version>3.0.2</version>
		</dependency>

添加书签


	/**
	 * 添加书签
	 * @param document pdf
	 * @param title 书签标题
	 * @param pageIndexs 书签,key 书签页,value 书签名
	 */
	public static void doBook(PDDocument document, String title, LinkedHashMap<Integer, String> pageIndexs) {
		PDDocumentOutline documentOutline = new PDDocumentOutline();
		document.getDocumentCatalog().setDocumentOutline(documentOutline);
		documentOutline.openNode();

		PDOutlineItem pagesOutline = new PDOutlineItem();
		pagesOutline.openNode();
		pagesOutline.setTitle(title);

		documentOutline.addLast(pagesOutline);
		for (Entry<Integer, String> e : pageIndexs.entrySet()) {
			PDPageDestination pageDestination = new PDPageFitWidthDestination();
			pageDestination.setPage(document.getPage(e.getKey()));

			PDOutlineItem bookmark = new PDOutlineItem();
			bookmark.setDestination(pageDestination);
			bookmark.setTitle(e.getValue());
			pagesOutline.addLast(bookmark);
		}

		PDPageDestination pageDestination = new PDPageFitWidthDestination();
		pageDestination.setPage(document.getPage(document.getNumberOfPages() - 1));

		//添加尾页,用于书签跳转,可去除
		PDOutlineItem bookmark = new PDOutlineItem();
		bookmark.setDestination(pageDestination);
		bookmark.setTitle("end尾页");
		
		pagesOutline.addLast(bookmark);
	}

合并pdf


	private static void combine(List<CombineEntity> files, File dist) throws IOException {

		try (PDDocument document = new PDDocument()) {
			LinkedHashMap<Integer, String>	books		= new LinkedHashMap<Integer, String>();
			int								bookIndex	= 0;
			for (int index = 0; index < files.size(); index++) {
				CombineEntity	com			= files.get(index);
				PDDocument		d			= Loader.loadPDF(com.file);

				int				pageNumber	= d.getNumberOfPages();
				int	start	= 0;
				int	end		= pageNumber;
				if (com.start != com.end) {
					start	= com.start;
					end		= com.end;
				}
				for (int i = start; i < end; i++) {
					document.importPage(d.getPage(i));
				}
				books.put(bookIndex, com.file.getName());
				bookIndex += (end - start);
			}
			// 添加书签
			PDFUtils.doBook(document, "book marks", books);
			document.save(dist);
		}

	}

	@Data
	@AllArgsConstructor
	@NoArgsConstructor
	public static class CombineEntity {
		private int		start;
		private int		end;
		private File	file;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值