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 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、工具类


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依赖

 <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、工具类

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依赖

<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、添加图片的代码

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();

Java Jacob 是一个 Java 与 Microsoft Office 交互的开源项目。它可以实现 Java 与 Office 应用程序(如 WordExcel、PowerPoint)之间的互操作,包括打开、读取、编辑和保存文档。如果您需要对 PDF 文件添加水印,可以使用 iText 库。下面是一个简单的示例代码: ```java import java.io.File; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfWriter; public class AddWatermark { public static void main(String[] args) { try { // 创建文档对象 Document document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File("test.pdf"))); document.open(); // 添加水印 PdfContentByte content = writer.getDirectContent(); Font font = new Font(Font.FontFamily.HELVETICA, 40); Paragraph watermark = new Paragraph("Confidential", font); watermark.setAlignment(Element.ALIGN_CENTER); content.beginText(); float width = PageSize.A4.getWidth(); float height = PageSize.A4.getHeight(); content.showTextAligned(Element.ALIGN_CENTER, watermark, width / 2, height / 2, 45); content.endText(); // 关闭文档 document.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码使用 iText 库创建了一个名为 "test.pdf" 的 PDF 文件,并在其添加了一个名为 "Confidential" 的水印。如果您需要更改水印的样式或位置,请修改上述代码的相应参数即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值