Java代码利用aspose-words将word文档转换成pdf和图片格式(PNG,JPG,JPEG破解 无水印)

发现问题:

    最近在写项目中遇到一个问题,是需要将一个word转为图片  展示到前端,在网上搜索好久,苦得一法,简单 高效的转化图片。

1.首先下载aspose-words-15.8.0-jdk16.jar包

在我的网盘里 我已无私贡献

链接:https://pan.baidu.com/s/1LiTGjRX72K26ABnkR1rdAw 
提取码:00j0 
2.直接上代码啊  想什么想

package com.li;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;

import com.aspose.words.Document;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import sun.misc.BASE64Encoder;

public class Test {
    public static void main(String[] args){
    	
    	//word2pdf("C:/Users/Administrator/Desktop/1.doc","C:/Users/Administrator/Desktop/xxxx.pdf");//word转pdf

    	
    	//word转图片格式
    	try {
			File file = new File("C:/Users/Administrator/Desktop/1.doc");

			InputStream inStream = new FileInputStream(file);
			List<BufferedImage> wordToImg = wordToImg(inStream,2);//
			BufferedImage mergeImage = mergeImage(false, wordToImg);

			ImageIO.write(mergeImage, "jpg", new File("C:/Users/Administrator/Desktop/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.png")); //将其保存在C:/imageSort/targetPIC/下
	       

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    

    /**
     * @Description: 验证aspose.word组件是否授权:无授权的文件有水印标记
     */
    public static boolean isWordLicense() {
        boolean result = false;
        try {
        	String s = "<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>";
        	ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes());
        	//InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.words.License license = new com.aspose.words.License();
            license.setLicense(inputStream);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    
    
    /**
     * @Description: word和txt文件转换图片
     */
    private static List<BufferedImage> wordToImg(InputStream inputStream, int pageNum) throws Exception {
        if (!isWordLicense()) {
            return null;
        }
        try {
            long old = System.currentTimeMillis();
            Document doc = new Document(inputStream);
            ImageSaveOptions options = new ImageSaveOptions(SaveFormat.PNG);
            options.setPrettyFormat(true);
            options.setUseAntiAliasing(true);
            options.setUseHighQualityRendering(true);
            int pageCount = doc.getPageCount();
            if (pageCount > pageNum) {//生成前pageCount张
                pageCount = pageNum;
            }
            List<BufferedImage> imageList = new ArrayList<BufferedImage>();
            for (int i = 0; i < pageCount; i++) {
                OutputStream output = new ByteArrayOutputStream();
                options.setPageIndex(i);
 
                doc.save(output, options);
                ImageInputStream imageInputStream = javax.imageio.ImageIO.createImageInputStream(parse(output));
                imageList.add(javax.imageio.ImageIO.read(imageInputStream));
 
            }
            return imageList;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    //outputStream转inputStream
    public static ByteArrayInputStream parse(OutputStream out) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos = (ByteArrayOutputStream) out;
        ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
        return swapStream;
    }

    

    /**
     * 合并任数量的图片成一张图片
     *
     * @param isHorizontal true代表水平合并,fasle代表垂直合并
     * @param imgs         待合并的图片数组
     * @return
     * @throws IOException
     */
    public static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) throws IOException {
        // 生成新图片
        BufferedImage destImage = null;
        // 计算新图片的长和高
        int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
        // 获取总长、总宽、最长、最宽
        for (int i = 0; i < imgs.size(); i++) {
            BufferedImage img = imgs.get(i);
            allw += img.getWidth();
 
            if (imgs.size() != i + 1) {
                allh += img.getHeight() + 5;
            } else {
                allh += img.getHeight();
            }
 
 
            if (img.getWidth() > allwMax) {
                allwMax = img.getWidth();
            }
            if (img.getHeight() > allhMax) {
                allhMax = img.getHeight();
            }
        }
        // 创建新图片
        if (isHorizontal) {
            destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
        } else {
            destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
        }
        Graphics2D g2 = (Graphics2D) destImage.getGraphics();
        g2.setBackground(Color.LIGHT_GRAY);
        g2.clearRect(0, 0, allw, allh);
        g2.setPaint(Color.RED);
 
        // 合并所有子图片到新图片
        int wx = 0, wy = 0;
        for (int i = 0; i < imgs.size(); i++) {
            BufferedImage img = imgs.get(i);
            int w1 = img.getWidth();
            int h1 = img.getHeight();
            // 从图片中读取RGB
            int[] ImageArrayOne = new int[w1 * h1];
            ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
            if (isHorizontal) { // 水平方向合并
                destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            } else { // 垂直方向合并
                destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            }
            wx += w1;
            wy += h1 + 5;
        }
 
 
        return destImage;
    }


    
    
    public static void word2pdf(String docPath,String savePath){

    	try {
    	String s = "<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>";
    	ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
    	License license = new License();
    	license.setLicense(is);
    	com.aspose.words.Document document = new com.aspose.words.Document(docPath);
    	document.save(new FileOutputStream(new File(savePath)),SaveFormat.PDF);
    	} catch (Exception e) {
    		
    		e.printStackTrace();
    	}
    }
    	
}

3.详细的jar和代码我打包放到资源下载里了,有需要可自行去下载。

下载地址:https://download.youkuaiyun.com/download/qq_41507845/11200632

### 使用 Aspose.Words API Word 文档并去除水印 #### 去除水印的操作方法 为了有效去除Word文档中的水印,可以利用Aspose.Words for .NET的强大功能来遍历文档对象模型(DOM),定位到特定类型的节点如形状(shape)或文本框(text box),这些通常是用来放置水印的位置。一旦识别出可能含有水印的元素,则可以通过编程方式将其移除。 对于基于文本的水印,如果它们被嵌入到了段落(paragraphs)之中作为特殊格式化的字符串,那么就需要更细致地解析每一个段落到找到那些具有典型水印特征的文字样式设置,并据此决定是否清除该部分内容[^1]。 ```csharp // 加载带有水印文档 Document doc = new Document("path/to/document_with_watermark.docx"); // 遍历所有Shape节点尝试匹配水印特性并移除 foreach (Node node in doc.GetChildNodes(NodeType.Shape, true)) { Shape shape = (Shape)node; // 判断shape是否可能是水印(这里可以根据实际需求调整判断逻辑) if (IsWaterMark(shape)) node.Remove(); } doc.Save("path/to/cleaned_document.docx"); ``` 上述代码片段展示了如何去掉文档内的形形式存在的水印;而对于纯文本型式的简单水印则需另外编写针对性更强的算法来进行检测与清理工作。 #### 文件格式之间的换 完成水印移除之后,就可以继续使用Aspose.Words轻松地把净化后的Word文档保存成多种目标格式之一。这一步骤非常直观,在调用了`Save()` 方法时只需指定相应的文件扩展名即可自动触发对应的渲染过程[^3]。 ```csharp // 将无水印版document另存为PDF格式 doc.Save("path/to/output_without_watermark.pdf", SaveFormat.Pdf); // 或者存为其他支持的目标格式... doc.Save("path/to/output_without_watermark.html", SaveFormat.Html); ``` 通过这种方式不仅可以高效地批量处理大量文档以满足不同应用场景下的输出要求,而且整个流程完全不需要依赖于任何第三方软件环境的支持,从而大大提高了自动化程度灵活性。
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值