java往word中添加水印,往excel中添加图片

通过aspose-words往word中添加水印

1、添加依赖

<dependency>
			<groupId>com.aspose</groupId>
			<artifactId>aspose-words</artifactId>
			<version>15.8.0</version>
			<scope>system</scope>
			<systemPath>${project.basedir}/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
		</dependency>

在src/main/resources/下添加证书文件license.xml

XML 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

2、工具类

java 复制代码
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Random;

import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.aspose.words.Document;
import com.aspose.words.HeaderFooter;
import com.aspose.words.HeaderFooterType;
import com.aspose.words.License;
import com.aspose.words.Node;
import com.aspose.words.Paragraph;
import com.aspose.words.SaveFormat;
import com.aspose.words.Section;
import com.aspose.words.Shape;
import com.aspose.words.ShapeType;

import lombok.extern.slf4j.Slf4j;


@Slf4j
public class WordUtil {

	 /**
     * 获取aspose证书
     */
    private static boolean getLicense() {
        boolean result = false;
        InputStream is = null;
        try {
            Resource resource = new ClassPathResource("license.xml");
            is = resource.getInputStream();
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    
    /**
     * 给word添加水印,铺满文本
     * @param path word文件路径
     * @param text 水印文字
     * @throws Exception
     */
    public static void waterMark(String path, String text) throws Exception {
    	Document doc = new Document(path);
    	
    	Paragraph watermarkPara = new Paragraph(doc);
    	//需要根据文本长度修改每行个数
    	for(int i=0; i<4; i++) {
    		for(int j=0; j<2; j++) {
    			Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
    	    	watermark.getTextPath().setText(text);
    	    	watermark.getTextPath().setFontFamily("simsun");
    	    	watermark.setWidth(200);
    	    	watermark.setHeight(40);
    	    	watermark.setRotation(-20);
    	    	watermark.setFillColor(new Color(220, 220, 220));
    	    	watermark.setStrokeColor(new Color(220, 220, 220));
    	    	watermark.setZOrder(-1);
    	    	watermark.setTop(i * 200);
    	    	watermark.setLeft(j * 260);
    	    	watermarkPara.appendChild(watermark);
    		}
    	}
    
    	for(Section sect: doc.getSections()) {
    		HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY);
    		if(header==null) {
    			header = new HeaderFooter(doc, HeaderFooterType.HEADER_PRIMARY);
    			sect.getHeadersFooters().add(header);
    		}
    		Node n = watermarkPara.deepClone(true);
    		header.appendChild(n);
    	}
    	doc.save(path);
    }
    
    /**
     * Word中添加图章
     * String srcPath, 源Word路径
     * String storePath, 添加图章后的路径
     * String sealPath, 图章路径(即图片)
     * String tabText, 在Word中盖图章的标识字符串,如:(签字/盖章)
     * int width, 图章宽度
     * int height, 图章高度
     * int leftOffset, 图章在编辑段落向左偏移量
     * int topOffset, 图章在编辑段落向上偏移量
     * boolean behind,图章是否在文字下面
     * @return void
     */
    public static void sealInWord(String srcPath, String storePath,String sealPath,String tabText,
                                  int width, int height, int leftOffset, int topOffset, boolean behind) throws Exception {
        File fileTem = new File(srcPath);
        InputStream is = new FileInputStream(fileTem);
        XWPFDocument document = new XWPFDocument(is);
        List<XWPFParagraph> paragraphs = document.getParagraphs();
        XWPFRun targetRun = null;
        for(XWPFParagraph  paragraph : paragraphs){
            if(!"".equals(paragraph.getText()) && paragraph.getText().contains(tabText)){
                List<XWPFRun> runs = paragraph.getRuns();
                targetRun = runs.get(runs.size()-1);
            }
        }
        if(targetRun != null){
            InputStream in = new FileInputStream(sealPath);//设置图片路径
            if(width <= 0){
                width = 100;
            }
            if(height <= 0){
                height = 100;
            }
            //创建Random类对象
            Random random = new Random();
            //产生随机数
            int number = random.nextInt(999) + 1;
            targetRun.addPicture(in, org.apache.poi.xwpf.usermodel.Document.PICTURE_TYPE_PNG, "Seal"+number, Units.toEMU(width), Units.toEMU(height));
            in.close();
            // 2. 获取到图片数据
            CTDrawing drawing = targetRun.getCTR().getDrawingArray(0);
            CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
 
            //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性
            CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "Seal"+number,
                    Units.toEMU(width), Units.toEMU(height),//图片大小
                    Units.toEMU(leftOffset), Units.toEMU(topOffset), behind);//相对当前段落位置 需要计算段落已有内容的左偏移
            drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性
            drawing.removeInline(0);//删除行内属性
        }
        document.write(new FileOutputStream(storePath));
        document.close();
    }
    /**
     * @param ctGraphicalObject 图片数据
     * @param deskFileName      图片描述
     * @param width             宽
     * @param height            高
     * @param leftOffset        水平偏移 left
     * @param topOffset         垂直偏移 top
     * @param behind            文字上方,文字下方
     * @return
     * @throws Exception
     */
    private static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject,
                                                String deskFileName, int width, int height,
                                                int leftOffset, int topOffset, boolean behind) {
        System.out.println(">>width>>"+width+"; >>height>>>>"+height);
        String anchorXML =
                "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
                        + "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"" + ((behind) ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
                        + "<wp:simplePos x=\"0\" y=\"0\"/>"
                        + "<wp:positionH relativeFrom=\"column\">"
                        + "<wp:posOffset>" + leftOffset + "</wp:posOffset>"
                        + "</wp:positionH>"
                        + "<wp:positionV relativeFrom=\"paragraph\">"
                        + "<wp:posOffset>" + topOffset + "</wp:posOffset>" +
                        "</wp:positionV>"
                        + "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>"
                        + "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
                        + "<wp:wrapNone/>"
                        + "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"" + deskFileName + "\"/><wp:cNvGraphicFramePr/>"
                        + "</wp:anchor>";
 
        CTDrawing drawing = null;
        try {
            drawing = CTDrawing.Factory.parse(anchorXML);
        } catch (XmlException e) {
            e.printStackTrace();
        }
        CTAnchor anchor = drawing.getAnchorArray(0);
        anchor.setGraphic(ctGraphicalObject);
        return anchor;
    }
    
}

3、破解版jar包下载地址

https://download.csdn.net/download/guzhangyu12345/89808281

通过aspose-cells将excel转为pdf

1、添加maven依赖

XML 复制代码
 <dependency>
			<groupId>aspose</groupId>
			<artifactId>aspose-cells</artifactId>
			<version>21.8</version>
			<scope>system</scope>
			<systemPath>${project.basedir}/libs/aspose-cells-21.8.jar</systemPath>
		</dependency>

2、工具类

java 复制代码
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.ibatis.javassist.CannotCompileException;
import org.apache.ibatis.javassist.ClassPool;
import org.apache.ibatis.javassist.CtClass;
import org.apache.ibatis.javassist.CtMethod;
import org.apache.ibatis.javassist.NotFoundException;

import com.aspose.cells.IndividualFontConfigs;
import com.aspose.cells.License;
import com.aspose.cells.LoadOptions;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;

/**
 * excel转换为pdf的工具类
 *
 * @author shmily
 */
public class Excel2PdfUtil {

    /**
     * 许可证字符串
     */
    private static final String LICENSE = "<License>" +
            "<Data>" +
            "<Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products>" +
            "<EditionType>Enterprise</EditionType>" +
            "<SubscriptionExpiry>20991231</SubscriptionExpiry>" +
            "<LicenseExpiry>20991231</LicenseExpiry>" +
            "<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>" +
            "</Data>" +
            "<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>" +
            "</License>";

    /**
     * 设置 license 去除水印
     */
    private static void setLicense() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(LICENSE.getBytes());
        License license = new License();
        license.setLicense(byteArrayInputStream);
    }


    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excelConvertPdf(String excelFilePath, String pdfFilePath, int[] convertSheets) {
        FileOutputStream fileOutputStream = null;
        try {
            pdfFilePath = pdfFilePath == null ? getPdfFilePath(excelFilePath) : pdfFilePath;
            // 设置License
            setLicense();
            // 读取excel文件
            Workbook wb = new Workbook(excelFilePath);
            fileOutputStream = new FileOutputStream(pdfFilePath);
            // 设置pdf格式
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setEmbedStandardWindowsFonts(true);
            pdfSaveOptions.setOnePagePerSheet(true);
            if (null != convertSheets) {
                printSheetPage(wb, convertSheets);
            }
            wb.save(fileOutputStream, pdfSaveOptions);
            fileOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fileOutputStream != null;
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * excel 转 pdf 二进制流
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excelConvertPdfByte(String excelFilePath, String pdfFilePath, int[] convertSheets) {
        FileOutputStream fileOutputStream = null;
        try {
            pdfFilePath = pdfFilePath == null ? getPdfFilePath(excelFilePath) : pdfFilePath;
            // 设置License
            setLicense();
            IndividualFontConfigs fontConfigs = new IndividualFontConfigs();
            fontConfigs.setFontFolder("/usr/share/fonts/win", false);
            LoadOptions loadOptions = new LoadOptions();
            loadOptions.setFontConfigs(fontConfigs);
            // 读取excel文件
            Workbook wb = new Workbook(excelFilePath);
            fileOutputStream = new FileOutputStream(pdfFilePath);
            // 设置pdf格式
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            if (null != convertSheets) {
                printSheetPage(wb, convertSheets);
            }
            wb.save(fileOutputStream, pdfSaveOptions);
            fileOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fileOutputStream != null;
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取 生成的 pdf 文件路径,默认与源文件同一目录
     *
     * @param excelPath excel文件
     * @return 生成的 pdf 文件
     */
    private static String getPdfFilePath(String excelPath) {
        int lastIndexOfPoint = excelPath.lastIndexOf(".");
        String pdfFilePath = "";
        if (lastIndexOfPoint > -1) {
            pdfFilePath = excelPath.substring(0, lastIndexOfPoint);
        }
        return pdfFilePath + ".pdf";
    }



    /**
     * 隐藏workbook中不需要的sheet页。
     *
     * @param sheets 显示页的sheet数组
     */
    private static void printSheetPage(Workbook wb, int[] sheets) {
        // 隐藏非第一个sheet页
        for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
            wb.getWorksheets().get(i).setVisible(false);
        }
        // 设置显示的sheet页
        if (null == sheets || sheets.length == 0) {
            wb.getWorksheets().get(0).setVisible(true);
        } else {
            for (int i = 0; i < sheets.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }
}

通过poi往excel中添加图片

1、添加maven依赖

XML 复制代码
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>5.3.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.3.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-contrib</artifactId>
            <version>3.6</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>

2、添加图片的代码

java 复制代码
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;

Workbook wb
Sheet sheet
FileInputStream img = new FileInputStream("logo.png");
int pictureIndex = wb.addPicture(IOUtils.toByteArray(img), Workbook.PICTURE_TYPE_PNG);


Drawing drawing = sheet.createDrawingPatriarch();
// 这几个参数的含义:图片距离左上角x轴方向距离,距离左上角y轴方向距离,距离右下角x轴方向距离,距离右下角y轴方向距离,左上角所在行数,左上角所在列数,右下角所在行数,右下角所在列数
ClientAnchor anchor = drawing.createAnchor(45 * Units.EMU_PER_POINT, 10 * Units.EMU_PER_POINT, -15 * Units.EMU_PER_POINT, -10 * Units.EMU_PER_POINT, 4, 1, 6, 2);
			
Picture picture = drawing.createPicture(anchor, pictureIndex);
img.close();
相关推荐
Theodore_10222 小时前
4 设计模式原则之接口隔离原则
java·开发语言·设计模式·java-ee·接口隔离原则·javaee
冰帝海岸3 小时前
01-spring security认证笔记
java·笔记·spring
世间万物皆对象4 小时前
Spring Boot核心概念:日志管理
java·spring boot·单元测试
没书读了4 小时前
ssm框架-spring-spring声明式事务
java·数据库·spring
小二·4 小时前
java基础面试题笔记(基础篇)
java·笔记·python
开心工作室_kaic5 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
懒洋洋大魔王5 小时前
RocketMQ的使⽤
java·rocketmq·java-rocketmq
武子康5 小时前
Java-06 深入浅出 MyBatis - 一对一模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据仓库·sql·mybatis·springboot·springcloud
转世成为计算机大神5 小时前
易考八股文之Java中的设计模式?
java·开发语言·设计模式
qq_327342736 小时前
Java实现离线身份证号码OCR识别
java·开发语言