spring boot pdf加水印 java
时间: 2024-01-29 17:03:03 浏览: 155
java代码,给pdf文件加水印
以下是使用Spring Boot和Java实现PDF加水印的示例代码:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
@SpringBootApplication
public class PdfWatermarkApplication {
public static void main(String[] args) {
SpringApplication.run(PdfWatermarkApplication.class, args);
}
public static void addWatermark(String inputFilePath, String outputFilePath, String watermarkText) {
try {
PdfReader reader = new PdfReader(inputFilePath);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFilePath));
BaseFont baseFont = BaseFont.createFont(ResourceUtils.getFile("classpath:font/arial.ttf").getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(baseFont, 50, Font.BOLD);
int totalPages = reader.getNumberOfPages();
for (int i = 1; i <= totalPages; i++) {
PdfContentByte content = stamper.getUnderContent(i);
content.beginText();
content.setFontAndSize(baseFont, 50);
content.setColorFill(BaseColor.LIGHT_GRAY);
content.showTextAligned(Element.ALIGN_CENTER, watermarkText, PageSize.A4.getWidth() / 2, PageSize.A4.getHeight() / 2, 45);
content.endText();
}
stamper.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
你可以调用`addWatermark`方法来给PDF文件添加水印。需要传入输入文件路径、输出文件路径和水印文本作为参数。
阅读全文