Java 在Excel中添加水印

这篇博客介绍了如何通过Java程序在Excel文件中创建水印效果。利用Spire.xls库,分别展示了如何绘制单一水印和多个水印,并提供了详细的代码示例。水印在普通视图下不可见,需在页面布局或打印预览模式下查看。
摘要由CSDN通过智能技术生成

在Excel中没有直接添加水印的功能,但依旧可以通过一定方式来实现类似水印效果。本文通过Java程序代码介绍具体实现方法。

程序环境:

  • 测试文档:Office Excel 2013
  • 编译环境:IntelliJ IDEA 2018
  • JDK版本:1.8.0
  • Excel库:Java系列spire.xls.jar 3.9.1(本次测试使用免费版)

 

Java全部测试代码

1.绘制单一水印效果

import com.spire.xls.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;

public class TextWatermark {
    public static void main(String[] args) {
        //加载Excel测试文档
        Workbook wb = new Workbook();
        wb.loadFromFile("test.xlsx");

        //设置文本和字体大小
        Font font = new Font("仿宋", Font.PLAIN, 40);

        for (int i =0;i<wb.getWorksheets().getCount();i++)
        {
            Worksheet sheet = wb.getWorksheets().get(i);
            //调用DrawText() 方法插入图片
            BufferedImage imgWtrmrk = drawText("内部专用", font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());

            //将图片设置为页眉
            sheet.getPageSetup().setLeftHeaderImage(imgWtrmrk);
            sheet.getPageSetup().setLeftHeader("&G");


            //将显示模式设置为Layout
            sheet.setViewMode(ViewMode.Layout);
        }

        //保存文档
        wb.saveToFile("TextWatermark.xlsx", ExcelVersion.Version2013);
    }
    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();

        //获取文本size
        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) / 2, -((int) height - liStrHeight) / 2);
        loGraphic.setFont(font);
        loGraphic.setColor(textColor);
        loGraphic.drawString(text, ((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);
        loGraphic.dispose();
        return img;
    }
}

2.绘制多个水印效果

import com.spire.xls.*;

import java.awt.*;
import java.awt.image.BufferedImage;

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

public class TextWatermark {
    public static void main(String[] args) {
        //加载Excel测试文档
        Workbook wb = new Workbook();
        wb.loadFromFile("test.xlsx");

        //设置文本和字体大小
        Font font = new Font("仿宋", Font.PLAIN, 20);

        for (int i =0;i<wb.getWorksheets().getCount();i++)
        {
            Worksheet sheet = wb.getWorksheets().get(i);
            //调用DrawText() 方法插入图片
            BufferedImage imgWtrmrk = drawText("内部专用     内部专用    内部专用    内部专用", font, Color.pink, Color.white, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());


            //将图片设置为页眉
            sheet.getPageSetup().setLeftHeaderImage(imgWtrmrk);
            sheet.getPageSetup().setLeftHeader("&G");

            //将显示模式设置为Layout
            sheet.setViewMode(ViewMode.Layout);
        }

        //保存文档
        wb.saveToFile("TextWatermark.xlsx", ExcelVersion.Version2013);
    }
    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();

        //获取文本size
        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;
    }
}

水印效果:

 

需要注意的是:在添加完水印效果后,查看文档时,在“普通视图”水印不可见,需在“页面布局”模式或“打印预览”模式下查看。

 

可以通过使用Java的Graphics2D类来添加文字水印到PDF文件。以下是一个示例代码: ```java import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDType1Font; public class AddTextWatermarkToPDF { public static void main(String[] args) { String inputFile = "input.pdf"; String outputFile = "output.pdf"; String watermarkText = "Confidential"; try { PDDocument document = PDDocument.load(new File(inputFile)); for (PDPage page : document.getPages()) { PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true); // set font and font size contentStream.setFont(PDType1Font.HELVETICA_BOLD, 72); // set text color to red contentStream.setNonStrokingColor(Color.RED); // rotate the text 45 degrees AffineTransform transform = new AffineTransform(); transform.rotate(Math.toRadians(45), 0, 0); contentStream.setTextMatrix(transform); // get the width and height of the text float textWidth = PDType1Font.HELVETICA_BOLD.getStringWidth(watermarkText) / 1000 * 72; float textHeight = PDType1Font.HELVETICA_BOLD.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * 72; // set the position of the text float x = (page.getMediaBox().getWidth() - textWidth) / 2; float y = (page.getMediaBox().getHeight() - textHeight) / 2; // write the text to the content stream contentStream.beginText(); contentStream.newLineAtOffset(x, y); contentStream.showText(watermarkText); contentStream.endText(); contentStream.close(); } // save the PDF document with the watermark document.save(new FileOutputStream(outputFile)); document.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例代码使用Apache PDFBox库来操作PDF文件。它打开一个PDF文件,遍历每个页面,然后在每个页面上添加一个旋转的、红色的、加粗的文本水印。如果需要更改水印文本、字体、颜色或位置,可以修改代码的相关行。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值