aspose.words -> dynamic editing of word document content

1. Import maven dependencies

1. Obtain  aspose-word-18.6-jdk16.jar  ;

2. Import the local warehouse;

mvn install:install-file -DgroupId=com.aspose -DartifactId=aspose-words -Dversion=18.8 -Dpackaging=jar -Dfile=D:/aspose-words-18.6-jdk16.jar

3. Introduce coordinates in the pom file.

<dependency>
     <groupId>com.aspose</groupId>
     <artifactId>aspose-words</artifactId>
     <version>18.8</version>
</dependency>

2. Introduce the cracked license file

1. Create license.xml under resources;

2. Copy the following content to license.xml.

<License>
  <Data>
    <Products>
      <Product>Aspose.Words for Java</Product>
    </Products>
    <EditionType>Enterprise</EditionType>
    <SubscriptionExpiry>29991231</SubscriptionExpiry>
    <LicenseExpiry>29991231</LicenseExpiry>
    <SerialNumber>---</SerialNumber>
  </Data>
  <Signature>---</Signature>
</License>

3. Word template editing

1. Field insertion: Insert -> Text Parts -> Field, the default category is "All", the domain name is "MergeField", and the domain name setting of the field attribute needs to insert the key;

2. Bookmark insertion: Insert -> Bookmark (insert a bookmark in the specified document area that needs to dynamically generate a list);

3. Put the edited template template.docx under resources.

Four. Code

import com.aspose.words.*;
import org.hibernate.validator.internal.util.privilegedactions.GetResource;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Word2PdfUtil {

    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = Word2PdfUtil.class.getClassLoader()
                    .getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void doc2Pdf(String Address, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        try {
            File file = new File(outPath);  // 新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(Address);   // Address是将要被转化的word文档
            doc.save(os, SaveFormat.PDF);   // 全面支持DOC, DOCX, OOXML, RTF HTML,
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static synchronized void editWord(HttpServletResponse response, FxbgParam fxbgParam) throws Exception {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        // 读取模板
        String templatePath = GetResource.class.getClassLoader().getResource("template/muban.docx").getPath().substring(1);
        Document doc = new Document(templatePath);
        DocumentBuilder builder = new DocumentBuilder(doc);

        Font font = builder.getFont();

        // 基本情况
        BaseCondition baseCondition = fxbgParam.getBaseCondition();
        builder.moveToBookmark("jbqkImg");    // 光标移动到当前标签
        builder.insertImage(baseCondition.getInputStream(), 410, 300);
        builder.writeln("");
        doc.getRange().getBookmarks().remove("jbqkImg");    // 移除预导出的文档中的标签

        Boolean isPressured = false;

        // 合法性分析
        builder.moveToBookmark("hfxfx");    // 光标移动到当前标签
        StringBuilder sb = new StringBuilder();
        List<Hfxfx> hfxfxList = fxbgParam.getHfxfxList();
        for (int i = 0; i < hfxfxList.size(); i++) {
            Hfxfx hfxfx = hfxfxList.get(i);
            font.setBold(true); // 加粗
            font.setSize(15); // 字体大小
            builder.writeln("(" + digitalFormat(i + 1) + ")、" + hfxfx.getTcName() + "情况分析");
            if (hfxfx.getPressured()) {
                builder.insertImage(hfxfx.getInputStream(), 410, 300);
                builder.writeln("");
                font.setBold(false); // 加粗
                font.setSize(15); // 字体大小
                builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);   // 居中显示
                isPressured = hfxfx.getPressured();
                sb.append(hfxfx.getTcName() + "、");
            } else {
                font.setBold(false); // 加粗
                font.setSize(15); // 字体大小
                builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);   // 居中显示
            }
            builder.getParagraphFormat().setLineSpacing(0.2);   // 行距
            builder.writeln(hfxfx.getImgRemark());
            builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);   // 居左显示
        }
        doc.getRange().getBookmarks().remove("hfxfx");    // 移除预导出的文档中的标签

        // 模板中域值设定
        MailMerge mailMerge = doc.getMailMerge();
        String[] keys = {"address", "lon", "lat", "yxArea", "yxdArea", "use", "xzTime", "allRemark", "ztjl", "bgr", "bgsj"};
        String address = baseCondition.getAddress();    // 规划预选址任务的地址位于
        String lon = baseCondition.getDj();    // 东经
        String lat = baseCondition.getBw();    // 北纬
        String yxArea = baseCondition.getYxArea(); // 预选区域面积
        String yxdArea = baseCondition.getYxdArea();    // 预选定区域面积
        String use = baseCondition.getUse();    // 预选址用途
        String xzTime = baseCondition.getTime(); // 预选址时间
        OverallConclusion overallConclusion = fxbgParam.getOverallConclusion();

        String allRemark = "";
        String ztjl = "根据已有数据分析结果,规划选址预选定区合理,无压占。";   // 总体结论
        if (isPressured) {
            allRemark = "预选定区域压占" + sb.toString();
            ztjl = "根据已有数据分析结果,规划选址预选定区域不合理,有压占土地利用现状图层,还需调整。";
        }
        String bgr = overallConclusion.getBgr();    // 报告人
        String bgsj = overallConclusion.getBgTime();   // 报告时间
        String[] values = {address, lon, lat, yxArea, yxdArea, use, xzTime, allRemark.substring(0, allRemark.length() - 1) + "。", ztjl, bgr, bgsj};
        mailMerge.execute(keys, values);
        FileUtils.createFolder(SwapFileServiceImpl.pdfExportPath);
        doc.save("D:\\系统分析报告.pdf", SaveFormat.PDF);
        downloadPdf(response);
    }

    private static void downloadPdf(HttpServletResponse response) throws Exception {
        FileInputStream inputStream = new FileInputStream(new File("D:\\系统分析报告.pdf"));
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/zip;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode("系统分析报告.pdf", "UTF-8"))));
            byte[] buffer = new byte[1024 * 10];
            int read;
            while ((read = inputStream.read(buffer, 0, 1024 * 10)) != -1) {
                out.write(buffer, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
            inputStream.close();
			// 下载完成后是否删除文件
        }
    }

}

 

Guess you like

Origin blog.csdn.net/weixin_42629433/article/details/109120293