使用java代码给Excel加水印,代码全,进阶版

以下代码,亲测可以跑通
1、上一篇博客用了Apache POI库3.8的版本的形式对Excel加了水印,但是最近主线版本用了4.1.2的形式,由于为了保持版本的兼容性,下面有开发了Apache POI的4.1.2的版本号的方案。
pom文件为:

 <dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml-schemas</artifactId>
            <version>1.4</version>
        </dependency>

    </dependencies>

测试类及主要 功能代码:

package com.msl;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

import static java.awt.image.BufferedImage.TYPE_INT_ARGB;

public class ExcelWatermark0905 {
    public static void main(String[] args) {
        // 输入Excel文件路径
        //   String inputFile = "/Users/navyliu/Downloads/input/附件2-3:企业资产转让业务尽职调查报告(申请机构_业务部门填写)1.xlsx";
       //  String inputFile = "/Users/navyliu/Downloads/input/kxkj.xlsx";
        // String inputFile = "/Users/navyliu/Downloads/input/test.xlsx";
      String inputFile = "/Users/navyliu/Downloads/input/315.xlsx";

        // 输出Excel文件夹路径
        String outputFolder = "/Users/navyliu/Downloads/output";
        // 水印文字
        String watermarkText = "我是水印文字";

        try {
            FileInputStream fis = new FileInputStream(inputFile);
            XSSFWorkbook workbook = new XSSFWorkbook(fis);

            // 设置文本和字体大小
            Font font = new Font("宋体",Font.PLAIN,36);
//            XXSFont font = workbook.createFont();
//            font.setFontName("仿宋");
//            font.setFontHeightInPoints((short) 20);

            int height = 467;
            int width = 987;
            BufferedImage watermarkImage = drawText(watermarkText, font, Color.orange, Color.white, height, width);

            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            ImageIO.write(watermarkImage, "png", byteArrayOut);
            int pictureIdx = workbook.addPicture(byteArrayOut.toByteArray(), Workbook.PICTURE_TYPE_PNG);

            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                   XSSFSheet  xssfSheet =  workbook.getSheetAt(i);
                   String rID = xssfSheet.addRelation(null, XSSFRelation.IMAGE_PNG, workbook.getAllPictures().get(pictureIdx))
                        .getRelationship().getId();
                //set background picture to sheet
                xssfSheet.getCTWorksheet().addNewPicture().setId(rID);

               }

            // 保存带水印的Excel到输出文件夹
            File outputDir = new File(outputFolder);
            if (!outputDir.exists()) {
                outputDir.mkdirs();
            }
            String outputFilePath = outputFolder + "/output2.xlsx";
            FileOutputStream fos = new FileOutputStream(outputFilePath);
            workbook.write(fos);
            fos.close();

            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static BufferedImage drawText(String text, Font font, Color textColor, Color backColor, double height, double width) {
        BufferedImage img = new BufferedImage((int) width, (int) height, TYPE_INT_ARGB);
        Graphics2D loGraphic = img.createGraphics();

        FontMetrics loFontMetrics = loGraphic.getFontMetrics(font);
        int liStrWidth = loFontMetrics.stringWidth(text);
        int liStrHeight = loFontMetrics.getHeight();

        loGraphic.setColor(backColor);
        loGraphic.fillRect(0, 0, (int) width, (int) height);
        loGraphic.translate(((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);
        loGraphic.rotate(Math.toRadians(-45));
        loGraphic.translate(-((int) width - liStrWidth) / 4, -((int) height - liStrHeight) / 4);
        loGraphic.setFont(font);
        loGraphic.setColor(textColor);
        loGraphic.drawString(text, ((int) width - liStrWidth) / 4, ((int) height - liStrHeight) / 2);
        loGraphic.drawString(text, ((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 4);
        loGraphic.drawString(text, ((int) width - liStrWidth) / 6, ((int) height - liStrHeight) / 20);
        loGraphic.dispose();
        return img;
    }
}


执行后的结果截图:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用 Java 语言实现给 PDF 文件水印代码: ```java import com.itextpdf.kernel.color.Color; import com.itextpdf.kernel.geom.Rectangle; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfPage; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.canvas.PdfCanvas; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.property.TextAlignment; import java.io.File; import java.io.IOException; public class PdfWatermark { public static void main(String[] args) throws IOException { String srcFile = "document.pdf"; // 原始 PDF 文件 String destFile = "document_with_watermark.pdf"; // 水印后的 PDF 文件 String watermark = "Confidential"; // 要添加水印文本 addWatermark(srcFile, destFile, watermark); // 调用添加水印的方法 } public static void addWatermark(String srcFile, String destFile, String watermark) throws IOException { PdfDocument pdfDoc = new PdfDocument(new PdfReader(srcFile), new PdfWriter(destFile)); Document doc = new Document(pdfDoc); for (int pageNum = 1; pageNum <= pdfDoc.getNumberOfPages(); pageNum++) { PdfPage page = pdfDoc.getPage(pageNum); Rectangle pageSize = page.getPageSize(); PdfCanvas canvas = new PdfCanvas(page); canvas.beginText(); canvas.setFontAndSize(null, 50); canvas.setColor(Color.GRAY, true); canvas.setTextMatrix(pageSize.getWidth() / 2, pageSize.getHeight() / 2); canvas.showTextAligned(new Paragraph(watermark).setBold().setFontColor(Color.GRAY).setTextAlignment(TextAlignment.CENTER), pageSize.getWidth() / 2, pageSize.getHeight() / 2, pageNum, TextAlignment.CENTER, com.itextpdf.kernel.geom.VerticalAlignment.MIDDLE, 45); canvas.endText(); } doc.close(); System.out.println("水印添加成功!"); } } ``` 以上代码中,我们使用了 iText 库来操作 PDF 文件。在添加水印时,我们首先打开原始 PDF 文件,并创建一个 Document 对象。然后,我们遍历 PDF 文件中的所有页面,为每个页面添加水印。为了添加水印,我们使用了 PdfCanvas 类,它提供了一组方法来绘制文本、图形等。在我们的例子中,我们使用 beginText() 方法开始绘制文本,setFontAndSize() 方法设置字体和字号,setColor() 方法设置颜色,setTextMatrix() 方法设置文本的位置,showTextAligned() 方法绘制文本,并使用 endText() 方法结束绘制。最后,我们使用 Document 对象的 close() 方法关闭 PDF 文件,并输出一条水印添加成功的信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值