首页 > 编程知识 正文

java去除pdf水印,spring initializingbean使用场景

时间:2023-05-06 05:17:54 阅读:249427 作者:3247

package com.xian.util;

import java.awt.Color;

import java.io.FileOutputStream;

import java.io.IOException;

import com.lowagie.text.DocumentException;

import com.lowagie.text.Element;

import com.lowagie.text.Image;

import com.lowagie.text.pdf.BaseFont;

import com.lowagie.text.pdf.PdfContentByte;

import com.lowagie.text.pdf.PdfReader;

import com.lowagie.text.pdf.PdfStamper;

/**

* 给PDF 加水印功能(文字水印和图片水印)

*

* @author jddhd

*/

public class PdfUtil {

/**

* 添加图片和文字水印

*

* @param srcFile 待加水印文件

* @param destFile 加水印后存放地址

* @param text 加水印的文本内容

* @param textWidth 文字横坐标

* @param textHeight 文字纵坐标

* @param imgFile 加水印图片文件

* @param imgWidth 图片横坐标

* @param imgHeight 图片纵坐标

* @throws IOException

* @throws DocumentException

*/

public static void addWaterMark(String srcFile, String destFile, String text, int textWidth, int textHeight,

String imgFile, int imgWidth, int imgHeight) throws IOException, DocumentException {

// 待加水印的文件

PdfReader reader = new PdfReader(srcFile);

// 加完水印的文件

PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));

// 设置字体

BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

// PDF总页数

int total = reader.getNumberOfPages() + 1;

// 循环对每页插入水印

PdfContentByte content;

for (int i = 1; i < total; i++) {

// 水印在之前文本之上

content = stamper.getOverContent(i);

// 图片水印

if (imgFile != null) {

Image image = null;

if (imgFile != null) {

image = Image.getInstance(imgFile);

image.setAbsolutePosition(imgWidth, imgHeight);

// 设置图片的显示大小

image.scaleToFit(100, 125);

}

content.addImage(image);

}

// 文字水印

if (text != null) {

content.beginText();

// 设置颜色 默认为蓝色

content.setColorFill(Color.BLUE);

// 设置字体及字号

content.setFontAndSize(font, 38);

// 设置起始位置

content.setTextMatrix(textWidth, textHeight);

// 中间水印

content.showTextAligned(Element.ALIGN_LEFT, text, textWidth, textHeight, 45);

// 底部水印

for (int k = 0; k < text.length(); k++) {

// 距离底边的距离

content.setTextRise(10);

// 将char转成字符串

content.showText(String.valueOf(text.charAt(k)));

}

content.endText();

}

}

stamper.close();

}

public static void main(String[] args) throws DocumentException, IOException {

String iconPath = "d:/test/icon/icon.png";

String srcImgPath = "d:/test/upload/temp/test.pdf";

String targerPath = "d:/test/upload/file/test.pdf";

PdfUtil.addWaterMark(srcImgPath, targerPath, "得瑟的ERP", 200, 300, iconPath, 400, 100);

}

}

VSCode断点调试CMake工程项目的实现步骤win7电脑文件夹如何加密怎么使用Python对疫情数据进行可视化分析

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。