Java給PDF加水印并合并多個(gè)文件
前言
本文基于itext7實(shí)現(xiàn)pdf加水印和合并的操作。實(shí)際上在我們實(shí)際項(xiàng)目應(yīng)用中,對(duì)于pdf的操作也是比較常見(jiàn)的,我上一個(gè)項(xiàng)目中就有將結(jié)果轉(zhuǎn)成pdf導(dǎo)出的需求。
準(zhǔn)備環(huán)境
jdk8,idea2020.1.1,maven3
代碼
添加依賴
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.5.4</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext7-core</artifactId> <version>7.1.16</version> </dependency>
工具類
圖片水印實(shí)體
import lombok.Data; import lombok.ToString; /** * 文字水印 * * @author mrcode */ @Data @ToString public class ImageWatermark { /** * 圖片所在絕對(duì)路徑 */ private String path; /** * 透明度 0-1(完全透明-不透明) */ private float opacity = 0.5F; }
文字水印實(shí)體
import com.itextpdf.io.font.constants.StandardFonts; import lombok.Data; import lombok.ToString; /** * 文字水印 * * @author mrcode */ @Data @ToString public class TextWatermark { /** * 文字水印,多行可使用 \n 換行 */ private String text; /** * 透明度 0-1(完全透明-不透明) */ private float opacity = 0.5F; /** * 顏色:只支持 RGB; 為空則默認(rèn)為黑色;比如 0,0,0; * <pre> * 建議使用 rgba 提供用戶選擇,后面的 a 的數(shù)值用于透明度的設(shè)置,展示的顏色和水印效果類似 * </pre> */ private String color; /** * 旋轉(zhuǎn)角度 */ private float radAngle = 0F; /** * 字體文件路徑;如果為空,則使用標(biāo)準(zhǔn)的英文字體 StandardFonts.HELVETICA * <pre> * 支持: afm、pfm、ttf、otf、woff、woff2 * </pre> * * @see StandardFonts#HELVETICA */ private String fontPath; /** * 字號(hào)大小, */ private int fontSize = 30; /** * 文本平鋪方式: 1:文本水平垂直居中 2:頁(yè)面平鋪 */ private int tileMode = 1; /** * 頁(yè)面平鋪:文字水平間隔;默認(rèn)為 50 */ private Integer pageModeOfHorizontalInterval; /** * 頁(yè)面平鋪:文字垂直間隔; 建議至少為字體大小(默認(rèn)為字體大?。?,如果有旋轉(zhuǎn),則合理的高度是 (文字個(gè)數(shù) * 文字高度) */ private Integer pageModeOfVerticalInterval; }
添加水印和背景的工具類
import com.itextpdf.io.font.PdfEncodings; import com.itextpdf.io.font.constants.StandardFonts; import com.itextpdf.io.image.ImageData; import com.itextpdf.io.image.ImageDataFactory; import com.itextpdf.kernel.colors.DeviceRgb; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.geom.Rectangle; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfPage; import com.itextpdf.kernel.pdf.PdfReader; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.canvas.PdfCanvas; import com.itextpdf.kernel.pdf.extgstate.PdfExtGState; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.property.TextAlignment; import com.itextpdf.layout.property.VerticalAlignment; import java.io.IOException; /** * PDF 水印添加 * * @author mrcode * @date 2021/10/22 21:27 */ public class PdFWatermarkUtil { /** * 添加文字水?。?默認(rèn)為居中添加 * * @param watermark * @param srcPath 原始 PDF 文件絕對(duì)路徑 * @param destPath 添加完水印后的 PDF 存放路徑 */ public static void addWatermark(TextWatermark watermark, String srcPath, String destPath) throws IOException { PdfDocument pdfDoc = new PdfDocument(new PdfReader(srcPath), new PdfWriter(destPath)); Document doc = new Document(pdfDoc); PdfFont font = getPdfFont(watermark.getFontPath()); // 設(shè)置文字水印樣式 final String text = watermark.getText(); final int fontSize = watermark.getFontSize(); Paragraph paragraph = new Paragraph(text) .setFont(font) // .setFontColor(new DeviceRgb(0, 0, 0)) .setOpacity(watermark.getOpacity()) // 字體透明度 0-1 完全透明~不透明 .setFontSize(fontSize); // 字體大小 final String color = watermark.getColor(); // 設(shè)置 RGB 顏色 if (color != null) { final String[] rgbs = color.split(","); final DeviceRgb deviceRgb = new DeviceRgb( Integer.parseInt(rgbs[0].trim()), Integer.parseInt(rgbs[1].trim()), Integer.parseInt(rgbs[2].trim())); paragraph.setFontColor(deviceRgb); } // 獲取水印文字寬度 final float textWidth = font.getWidth(text, fontSize); // 文字高度則是字體大小 final float textHeight = fontSize; final int tileMode = watermark.getTileMode(); final int pageModeOfHorizontalInterval = watermark.getPageModeOfHorizontalInterval() == null ? 50 : watermark.getPageModeOfHorizontalInterval(); final int pageModeOfVerticalInterval = watermark.getPageModeOfVerticalInterval() == null ? (int) textHeight : watermark.getPageModeOfVerticalInterval(); for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) { PdfPage pdfPage = pdfDoc.getPage(i); // 獲取頁(yè)面大小,考慮頁(yè)面旋轉(zhuǎn) Rectangle pageSize = pdfPage.getPageSizeWithRotation(); // 當(dāng)頁(yè)面有旋轉(zhuǎn)時(shí),內(nèi)容自動(dòng)旋轉(zhuǎn) pdfPage.setIgnorePageRotationForContent(true); // 水印水平垂直居中 if (tileMode == 1) { // 計(jì)算添加的位置坐標(biāo):這里使用居中位置,水平垂直居中 float x = (pageSize.getLeft() + pageSize.getRight()) / 2; float y = (pageSize.getTop() + pageSize.getBottom()) / 2; // 參數(shù)分別為:文本、x 坐標(biāo)、y 坐標(biāo)、添加到底幾頁(yè)、文本水平對(duì)齊方式、文本垂直對(duì)齊方式、旋轉(zhuǎn)弧度 doc.showTextAligned(paragraph, x, // 文本所在 x y 坐標(biāo),文字將圍繞這個(gè)點(diǎn)進(jìn)行對(duì)齊或則旋轉(zhuǎn) y, i, // 添加到 PDF 第幾頁(yè) TextAlignment.CENTER, // 文本水平對(duì)齊方式 VerticalAlignment.TOP, // 文本垂直對(duì)齊方式 // 將 角度 轉(zhuǎn)換為 弧度 (float) Math.toRadians(watermark.getRadAngle())); } else { // 水印按照設(shè)置平鋪?lái)?yè)面 // 注意這里的坐標(biāo)點(diǎn)是 文字中心點(diǎn),所以寬度需要增加文字自己的寬度,否則會(huì)重合在一起 for (float posX = 0f; posX < pageSize.getWidth(); posX = posX + textWidth + pageModeOfHorizontalInterval) { for (float posY = pageModeOfVerticalInterval; posY < pageSize.getHeight(); posY = posY + pageModeOfVerticalInterval) { // 參數(shù)分別為:文本、x 坐標(biāo)、y 坐標(biāo)、添加到底幾頁(yè)、文本水平對(duì)齊方式、文本垂直對(duì)齊方式、旋轉(zhuǎn)弧度 doc.showTextAligned(paragraph, posX, // 文本所在 x y 坐標(biāo),文字將圍繞這個(gè)點(diǎn)進(jìn)行對(duì)齊或則旋轉(zhuǎn) posY, i, // 添加到 PDF 第幾頁(yè) TextAlignment.CENTER, // 文本水平對(duì)齊方式 VerticalAlignment.TOP, // 文本垂直對(duì)齊方式 // 將 角度 轉(zhuǎn)換為 弧度 (float) Math.toRadians(watermark.getRadAngle())); } } } } doc.close(); } /** * 獲取字體,支持 afm、pfm、ttf、otf、woff、woff2 字體,ttc 目前直接報(bào)錯(cuò) * * @param fontPath 字體文件絕對(duì)路徑,如果為空則返回默認(rèn)的英文字體 * @return */ private static PdfFont getPdfFont(String fontPath) throws IOException { if (fontPath == null) { return PdfFontFactory.createFont(StandardFonts.HELVETICA); } return PdfFontFactory.createFont( fontPath, // 水平書(shū)寫(xiě) PdfEncodings.IDENTITY_H, // 是否將字體嵌入到目標(biāo)文檔中: 如果可能,嵌入字體 PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED); } /** * 添加圖片水??; 默認(rèn)為居中添加 * * @param watermark * @param srcPath 原始 PDF 文件絕對(duì)路徑 * @param destPath 添加完水印后的 PDF 存放路徑 */ public static void addWatermark(ImageWatermark watermark, String srcPath, String destPath) throws IOException { PdfDocument pdfDoc = new PdfDocument(new PdfReader(srcPath), new PdfWriter(destPath)); Document doc = new Document(pdfDoc); // 創(chuàng)建圖片 ImageData img = ImageDataFactory.create(watermark.getPath()); float w = img.getWidth(); float h = img.getHeight(); // 設(shè)置透明度 PdfExtGState gs1 = new PdfExtGState().setFillOpacity(watermark.getOpacity()); // 循環(huán)添加到每一頁(yè)的 PDF 中 for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) { PdfPage pdfPage = pdfDoc.getPage(i); // 獲取頁(yè)面大小,考慮頁(yè)面旋轉(zhuǎn) Rectangle pageSize = pdfPage.getPageSizeWithRotation(); // 當(dāng)頁(yè)面有旋轉(zhuǎn)時(shí),內(nèi)容自動(dòng)旋轉(zhuǎn) pdfPage.setIgnorePageRotationForContent(true); // 計(jì)算添加的位置坐標(biāo):這里使用居中位置,水平垂直居中 float x = (pageSize.getLeft() + pageSize.getRight()) / 2; float y = (pageSize.getTop() + pageSize.getBottom()) / 2; // 添加圖片水印使用 PdfCanvas over = new PdfCanvas(pdfDoc.getPage(i)); over.saveState(); over.setExtGState(gs1); // 添加圖片水?。何恢盟酱怪本又? over.addImageWithTransformationMatrix(img, w, 0, 0, h, x - (w / 2), y - (h / 2), false); over.restoreState(); } doc.close(); } }
文件合并添加頁(yè)碼工具類
import com.itextpdf.io.font.PdfEncodings; import com.itextpdf.io.font.constants.StandardFonts; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.geom.Rectangle; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfPage; import com.itextpdf.kernel.pdf.PdfReader; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.utils.PdfMerger; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.property.TextAlignment; import com.itextpdf.layout.property.VerticalAlignment; import java.io.IOException; import java.util.List; import cn.hutool.core.util.StrUtil; /** * @author mrcode * @date 2022/1/21 20:27 */ public class PDFUtil { /** * 合并多個(gè) PDF 文件為一個(gè) * * @param list 要合并的 PDF 文件絕對(duì)路徑列表 * @param toFile 合并后的 PDF 文件絕對(duì)路徑 * @throws IOException */ public static void merge(List<String> list, String toFile) throws IOException { final PdfDocument toPdf = new PdfDocument(new PdfWriter(toFile)); PdfMerger merger = new PdfMerger(toPdf); for (String file : list) { final PdfDocument pdfDocument = new PdfDocument(new PdfReader(file)); merger.merge(pdfDocument, 1, pdfDocument.getNumberOfPages()); pdfDocument.close(); } merger.close(); toPdf.close(); } /** * 添加頁(yè)碼; 在右下角添加 * * @param fontSize 文字大小,一般為 15 比較合適 * @param srcPath 原始 PDF 文件絕對(duì)路徑 * @param destPath 添加完水印后的 PDF 存放路徑 */ public static void addPageNumber(int fontSize, String srcPath, String destPath) throws IOException { PdfDocument pdfDoc = new PdfDocument(new PdfReader(srcPath), new PdfWriter(destPath)); Document doc = new Document(pdfDoc); PdfFont font = getPdfFont(null); // 文字高度則是字體大小 final float textHeight = fontSize; final int numberOfPages = pdfDoc.getNumberOfPages(); for (int i = 1; i <= numberOfPages; i++) { PdfPage pdfPage = pdfDoc.getPage(i); // 獲取頁(yè)面大小,考慮頁(yè)面旋轉(zhuǎn) Rectangle pageSize = pdfPage.getPageSizeWithRotation(); // 當(dāng)頁(yè)面有旋轉(zhuǎn)時(shí),內(nèi)容自動(dòng)旋轉(zhuǎn) pdfPage.setIgnorePageRotationForContent(true); // 構(gòu)建頁(yè)碼 final String text = StrUtil.format("{}/{}", i, numberOfPages); Paragraph paragraph = new Paragraph(text) .setFont(font) .setFontSize(fontSize); // 獲取文字寬度 final float textWidth = font.getWidth(text, fontSize); // 計(jì)算添加的位置坐標(biāo) // 定位到水平垂直居中 // float x = (pageSize.getLeft() + pageSize.getRight()) / 2; // 定位到右側(cè):根據(jù)文字寬度減少寬度,能動(dòng)態(tài)的根據(jù)文字寬度調(diào)整,讓文字不會(huì)超出屏幕外面 float x = pageSize.getRight() - textWidth; // bottom 是 0,+ 20 就是底部往上 20 // 定位到底部:根據(jù)文字高度動(dòng)態(tài)往上調(diào)整,不會(huì)超出屏幕外面; float y = pageSize.getBottom() + textHeight + 10; // 參數(shù)分別為:文本、x 坐標(biāo)、y 坐標(biāo)、添加到底幾頁(yè)、文本水平對(duì)齊方式、文本垂直對(duì)齊方式、旋轉(zhuǎn)弧度 doc.showTextAligned(paragraph, x, // 文本所在 x y 坐標(biāo),文字將圍繞這個(gè)點(diǎn)進(jìn)行對(duì)齊或則旋轉(zhuǎn) y, i, // 添加到 PDF 第幾頁(yè) TextAlignment.CENTER, // 文本水平對(duì)齊方式 VerticalAlignment.TOP, // 文本垂直對(duì)齊方式 // 將 角度 轉(zhuǎn)換為 弧度 (float) Math.toRadians(0)); } doc.close(); } /** * 獲取字體,支持 afm、pfm、ttf、otf、woff、woff2 字體,ttc 目前直接報(bào)錯(cuò) * * @param fontPath 字體文件絕對(duì)路徑,如果為空則返回默認(rèn)的英文字體 * @return */ private static PdfFont getPdfFont(String fontPath) throws IOException { if (fontPath == null) { return PdfFontFactory.createFont(StandardFonts.HELVETICA); } return PdfFontFactory.createFont( fontPath, // 水平書(shū)寫(xiě) PdfEncodings.IDENTITY_H, // 是否將字體嵌入到目標(biāo)文檔中: 如果可能,嵌入字體 PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED); } }
測(cè)試
測(cè)試加水印與背景
package com.example.pdf; import com.itextpdf.io.image.ImageData; import com.itextpdf.io.image.ImageDataFactory; import com.itextpdf.kernel.geom.Rectangle; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfPage; import com.itextpdf.kernel.pdf.PdfReader; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.canvas.PdfCanvas; import com.itextpdf.kernel.pdf.extgstate.PdfExtGState; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.property.TextAlignment; import com.itextpdf.layout.property.VerticalAlignment; public class Demo { public static final String DEST = "C:\\Users\\zhbcm\\Desktop\\readme1.pdf"; public static final String IMG = "E:\\圖片\\th.jpg"; public static final String SRC = "C:\\Users\\zhbcm\\Desktop\\readme.pdf"; public static void main(String[] args) throws Exception { new Demo().manipulatePdf(DEST); } protected void manipulatePdf(String dest) throws Exception { PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest)); Document doc = new Document(pdfDoc); // PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA); // 這個(gè)實(shí)體是宋體中文字體,只有 4, m // 字體文件源碼中只支持 afm、pfm、ttf、otf、woff、woff2,等你提供不支持的格式就會(huì)報(bào)錯(cuò),點(diǎn)進(jìn)去看源碼就知道了 // ttc 看到源碼中也支持,但是提供 ttc 就報(bào)錯(cuò),暫時(shí)沒(méi)深入看源碼如何報(bào)錯(cuò) // final PdfFont font = PdfFontFactory.createFont("C:\\temp\\songti.ttf", // // 水平書(shū)寫(xiě) // PdfEncodings.IDENTITY_H, // // 是否將字體嵌入到目標(biāo)文檔中 // // 該參數(shù)被 PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED 代替,true 對(duì)應(yīng) PREFER_EMBEDDED,如果可能,嵌入字體 // true); // 多行文本使用 \n 換行 Paragraph paragraph = new Paragraph("My watermark (中國(guó)強(qiáng)text) \n 中國(guó)") // .setFont(font) .setOpacity(0.1F) // 字體透明度 0-1 完全透明~不透明 .setFontSize(30); // 字體大小 ImageData img = ImageDataFactory.create(IMG); float w = img.getWidth(); float h = img.getHeight(); // 用于添加圖片水印,設(shè)置圖片水印透明度 PdfExtGState gs1 = new PdfExtGState().setFillOpacity(0.5f); // Implement transformation matrix usage in order to scale image for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) { PdfPage pdfPage = pdfDoc.getPage(i); // 獲取頁(yè)面大小,考慮頁(yè)面旋轉(zhuǎn) Rectangle pageSize = pdfPage.getPageSizeWithRotation(); // 當(dāng)頁(yè)面有旋轉(zhuǎn)時(shí),內(nèi)容自動(dòng)旋轉(zhuǎn) pdfPage.setIgnorePageRotationForContent(true); // 計(jì)算添加的位置坐標(biāo) float x = (pageSize.getLeft() + pageSize.getRight()) / 2; float y = (pageSize.getTop() + pageSize.getBottom()) / 2; // 添加圖片水印使用 PdfCanvas over = new PdfCanvas(pdfDoc.getPage(i)); over.saveState(); over.setExtGState(gs1); if (i % 2 == 1) { // 添加文本水印 // 參數(shù)分別為:文本、x 坐標(biāo)、y 坐標(biāo)、添加到第幾頁(yè)、文本水平對(duì)齊方式、文本垂直對(duì)齊方式、旋轉(zhuǎn)弧度 doc.showTextAligned(paragraph, x, y, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0); } else { // 添加圖片水印 over.addImageWithTransformationMatrix(img, w, 0, 0, h, x - (w / 2), y - (h / 2), false); } over.restoreState(); } doc.close(); } }
水印效果圖
背景效果圖
測(cè)試pdf合并
合并前
合并后
總結(jié)
到此這篇關(guān)于Java給PDF加水印并合并多個(gè)文件的文章就介紹到這了,更多相關(guān)Java PDF加水印合并內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java項(xiàng)目導(dǎo)出數(shù)據(jù)為 PDF 文件的操作代碼
一個(gè)小需求,需要將頁(yè)面上的數(shù)據(jù)導(dǎo)出為PDF,正常情況下這個(gè)需求需要讓前端來(lái)做,但是現(xiàn)在上面讓咱們后端來(lái)做,也沒(méi)問(wèn)題,這篇文章主要介紹了Java項(xiàng)目導(dǎo)出數(shù)據(jù)為 PDF 文件的操作代碼,需要的朋友可以參考下2022-12-12關(guān)于Spring3 + Mybatis3整合時(shí)多數(shù)據(jù)源動(dòng)態(tài)切換的問(wèn)題
這篇文章主要介紹了關(guān)于Spring3 + Mybatis3整合時(shí)多數(shù)據(jù)源動(dòng)態(tài)切換的問(wèn)題,需要的朋友可以參考下2017-04-04如何在JDK 9中更簡(jiǎn)潔使用 try-with-resources 語(yǔ)句
本文詳細(xì)介紹了自 JDK 7 引入的 try-with-resources 語(yǔ)句的原理和用法,以及介紹了 JDK 9 對(duì) try-with-resources 的改進(jìn),使得用戶可以更加方便、簡(jiǎn)潔的使用 try-with-resources 語(yǔ)句。,需要的朋友可以參考下2019-06-06Java接口方法默認(rèn)靜態(tài)實(shí)現(xiàn)代碼實(shí)例
這篇文章主要介紹了Java接口方法默認(rèn)靜態(tài)實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06mybatis-plus無(wú)法通過(guò)logback-spring輸出的解決方法
本文主要介紹了mybatis-plus無(wú)法通過(guò)logback-spring輸出,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11Java使用poi做加自定義注解實(shí)現(xiàn)對(duì)象與Excel相互轉(zhuǎn)換
這篇文章主要介紹了Java使用poi做加自定義注解實(shí)現(xiàn)對(duì)象與Excel相互轉(zhuǎn)換,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05Spring Boot 將yyyy-MM-dd格式的文本字符串直接轉(zhuǎn)換為L(zhǎng)ocalDateTime出現(xiàn)的問(wèn)題
這篇文章主要介紹了Spring Boot 將yyyy-MM-dd格式的文本字符串直接轉(zhuǎn)換為L(zhǎng)ocalDateTime出現(xiàn)的問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09