package com.export.utils;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import javax.swing.*;
import java.awt.*;
import java.io.*;
/**
* pdf 相关工具方法(添加水印)
**/
@Slf4j
public class PdfFileUtils {
@Test
public void pdfAddWaterRemark() throws IOException, DocumentException {
// 要输出的pdf文件
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(new File("E:/b.pdf")));
// 要输入的PDF文件
File file = new File("E:/c.pdf");
byte[] bytes = FileUtils.readFileToByteArray(file);
// 将pdf文件先加水印然后输出
byte[] bytes1= setWatermark( bytes, "内部机密文件,请勿外传!");
bos.write(bytes1);
bos.flush();
}
/**
* PDF加文字水印
* @param input 源pdf文件输入数组
* @param waterMarkName 水印文字
* @return 目标pdf的字节数组
* @throws DocumentException
* @throws IOException
*/
public static byte[] setWatermark( byte[] input, String waterMarkName) {
try(ByteArrayOutputStream bos=new ByteArrayOutputStream()){
PdfReader reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, bos);
// 获取总页数 +1, 下面从1开始遍历
int total = reader.getNumberOfPages() + 1;
// 使用classpath下面的字体库
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// 水印字体加粗
base.setPostscriptFontName(BaseFont.COURIER_BOLD);
// 水印间隔
int interval = 0;
// 这个position主要是为了在换行加水印时能往右偏移起始坐标
int position = 1;
JLabel label = new JLabel();
label.setText(waterMarkName);
FontMetrics metrics = label.getFontMetrics(label.getFont());
// 获取水印文字的高度和宽度
int textH = metrics.getHeight();
int textW = metrics.stringWidth(label.getText());
// 设置水印透明度
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.5f);
gs.setStrokeOpacity(0.5f);
for (int i = 1; i < total; i++) {
// 在内容下方加水印
PdfContentByte content = stamper.getUnderContent(i);
content.saveState();
content.setGState(gs);
// 设置字体和字体大小
content.beginText();
content.setFontAndSize(base, 20);
// 获取每一页的高度、宽度
com.itextpdf.text.Rectangle pageSizeWithRotation = reader.getPageSizeWithRotation(i);
float pageHeight = pageSizeWithRotation.getHeight();
float pageWidth = pageSizeWithRotation.getWidth();
// 根据纸张大小多次添加, 水印文字成30度角倾斜
for (int height = interval + textH; height < pageHeight; height = height + textH * 10) {
for (int width = interval + textW - position * 150; width < pageWidth + textW; width = width + textW + 80) {
content.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 30);
}
position++;
}
content.endText();
}
stamper.close();
reader.close();
return bos.toByteArray();
}catch (Exception e){
log.error("error",e);
return null;
}
}
}
Java相关pdf添加水印
你知道pdf识别文本软件哪个好吗
« 上一篇
免费好用的全文PDF翻译工具,推荐给你
下一篇 »