Java-Aspose实现Word文字替换(本地储存或浏览器下载)

目录

  • 1、加载Aspose包
  • 2、配置license
  • 3、实现

1、加载Aspose包

1、下载:
Aspose官网没有提供相应的maven地址,所有手动引入jar包:

  • aspose-words-18.10-jdk16.jar

下载地址:https://download.csdn.net/download/zhuocailing3390/76147206

2、配置lib目录:
在项目的resources目录下,创建lib目录,并且将下载的jar包放入其中

3、引入pom:
引入自定义配置的maven坐标:

	<dependencys>
        <dependency>
            <groupId>com.aspose.wordsgroupId>
            <artifactId>aspose-wordsartifactId>
            <version>words-18.10-jdk16version>
            <scope>systemscope>
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-words-18.10-jdk16.jarsystemPath>
        dependency>
    dependencys>

2、配置license

resources目录下创建license.xml文件,代码如下:

<License>
  <Data>
    <Products>
      <Product>Aspose.Total for JavaProduct>
      <Product>Aspose.Words for JavaProduct>
    Products>
    <EditionType>EnterpriseEditionType>
    <SubscriptionExpiry>20991231SubscriptionExpiry>
    <LicenseExpiry>20991231LicenseExpiry>
    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7SerialNumber>
  Data>
  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=Signature>
License>

3、实现

代码:

@Controller
@RequestMapping("/aspose")
public class AsposeController {

    @RequestMapping("/replaceByString")
    @ResponseBody
    public static void replaceByString() {
        try {
            if (!getLicense()) {
                throw new RuntimeException("文件替换失败!");
            }
            FindReplaceOptions options = new FindReplaceOptions();
            options.setMatchCase(false);
            // 方式一:直接指定原word位置
            Document document = new Document("C:\\Users\\LiGezZ\\Desktop\\test.docx");
            /*方式二:
            *如果原word在项目的resources目录下,可以使用ClassPathResource进行加载
            String path = "/word/test.docx";
            FileInputStream inputStream = new FileInputStream(new ClassPathResource(path).getFile());
            Document document = new Document(inputStream);
            */

            document.getRange().replace("${name}", "文件替换有限公司", options);

            // 存储方式一:将提交后的文件输出到指定目录,也可以直接在浏览器进行下载不进行本地储存
            File outFile = new File("C:\\Users\\LiGezZ\\Desktop\\testReplace.docx");
            try (FileOutputStream fos = new FileOutputStream(outFile )) {
                // 输出方式一:输出为word
                document.save(fos, SaveFormat.WORD_ML);

                // 输出方式二:输出为PDF,需要将输出文件的后缀修改为.pdf,比如:testReplace.pdf
                // document.save(fos, SaveFormat.PDF);
                
				/* 存储方式二:
                 * 如果是输出到浏览器直接下载
                 * 那么将FileOutputStream fos = new FileOutputStream(pdfFile)替换为
                 * ByteArrayOutputStream fos = new ByteArrayOutputStream()
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                byte[] buffer = fos.toByteArray();
                InputStream arrayInputStream = new ByteArrayInputStream(buffer);
                byte[] buf = new byte[4096];
                int len = -1;
                while ((len = arrayInputStream.read(buf)) != -1) {
                    response.getOutputStream().write(buf, 0, len);
                }
                */
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件替换失败!");
        }
    }
    // 验证aspose文件
	private static boolean getLicense() {
        boolean result = false;
        try (InputStream in = Doc2PdfUtil.class.getClassLoader()
                .getResourceAsStream("license.xml")) {
            // 需要引入com.aspose.words.License的包;
            License license = new License();
            license.setLicense(in);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

测试:

比如浏览器请求接口:http://localhost:9898/aspose/replaceByString
Java-Aspose实现Word文字替换(本地储存或浏览器下载)_第1张图片

你可能感兴趣的:(Java,开发技巧,word,文字替换,aspose)