Commit adf6bba2 by weiguanying

国结公共模块:dsp文件解析渲染、doc模板文件,docx生成pdf等

parents
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="dsp" />
<module name="doc" />
</profile>
</annotationProcessing>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="doc" options="-parameters" />
<module name="dsp" options="-parameters" />
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/doc/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/dsp/src/main/java" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="com.e-iceblue" />
<option name="name" value="e-iceblue" />
<option name="url" value="https://repo.e-iceblue.com/nexus/content/groups/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
This diff is collapsed. Click to expand it.
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.11</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.com.brilliance</groupId>
<artifactId>doc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>doc</name>
<description>doc</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--hutool工具依赖-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.3.6</version>
</dependency>
<!--文件转换相关依赖-->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.core</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.template</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document.docx</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.template.freemarker</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<!--word转pdf依赖-->
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>11.2.3</version>
</dependency>
<!--pdf转word依赖-->
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf</artifactId>
<version>9.1.4</version>
</dependency>
<!--https://mvnrepository.com/artifact/e-iceblue/spire.doc.free -->
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
<!--poi-tl word模板引擎 实现 word模板生成word文件-->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.1</version>
</dependency>
</dependencies>
<!-- 设置iceblue的仓库 -->
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package cn.com.brilliance.doc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DocApplication {
public static void main(String[] args) {
SpringApplication.run(DocApplication.class, args);
}
}
package cn.com.brilliance.doc.config;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* @Author weiguanying
* @Date 2023-02-20
* @Description configClass
*/
@Configuration
@PropertySource("classpath:application.yml")
@Getter
public class DocBean {
@Value("${faceLetter.filePath}")
private String filePath;
@Value("${faceLetter.templatesPath}")
private String templatesPath;
@Value("${spire.key}")
private String spireKey;
}
package cn.com.brilliance.doc.controller;
import cn.com.brilliance.doc.config.DocBean;
import cn.com.brilliance.doc.service.PreviewService;
import cn.com.brilliance.doc.service.WordTemplateService;
import cn.com.brilliance.doc.utils.WordToPDF;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Map;
/**
* @auhotr weiguanying
* @date 20230220
* @description 文件处理
*/
@RestController
@RequestMapping("/api")
@Slf4j
public class FileController {
@Autowired
private PreviewService previewService;
@Autowired
private WordTemplateService wordTemplateService;
@Autowired
private DocBean docBean;
/**
* @auhotr weiguanying
* @date 20230220
* @description 返回文件base64字符串对象给前端做预览
*/
@PostMapping("/filePreview")
public String filePreview(@RequestParam("fileName") String fileName) throws IOException {
return previewService.preview(fileName);
}
/**
* @param templateName 模板名称
* @return base64字符串
* @throws IOException
* @auhotr weiguanying
* @date 20230220
* @description 通过docx模板文件生成docx并返回前端预览
*/
@PostMapping("/templatePreview")
public String templatePreview(@RequestParam("templateName") String templateName) throws IOException {
String fileName = wordTemplateService.docxTemplateToDocx(templateName);
return previewService.preview(fileName);
}
@PostMapping("/wordToPdf")
public String wordToPdf(@RequestParam("filePath") String filePath, @RequestParam("targetPath") String targetPath) {
filePath = docBean.getFilePath() + filePath;
targetPath = docBean.getFilePath() + targetPath;
String licenseKey = docBean.getSpireKey();
WordToPDF wordToPDF = new WordToPDF();
wordToPDF.doxcTopdf(filePath, targetPath, licenseKey);
return targetPath;
}
/**
* word-docx模板生成word-docx
* @param paramMap map
* @return
* {"fileName":"222.docx","templateName":"222.docx","templateData":{"title":"1111","date":"2222","brNo":"3333","amount":"4444","no":"4444","bankName":"BankName"},"text":"text111","year":"2023","month":"02","day":"27","num1":"num111","num2":"num222","lines":"Java平台由Java虚拟机"}
*/
@PostMapping("templateWord")
public String wordTemplateToWord(@RequestBody Map<String, Object> paramMap) {
return wordTemplateService.poiCreateWord(paramMap);
}
}
package cn.com.brilliance.doc.controller;
import cn.com.brilliance.doc.config.DocBean;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
/**
* @Author weiguanying
* @Date 2023-02-20
* download pdf file
*/
@RestController
@RequestMapping("/api")
@Slf4j
public class PdfDownLoadController {
private static final Logger logger = LoggerFactory.getLogger(PdfDownLoadController.class);
// 注入配置类
@Autowired
private DocBean docBean;
@RequestMapping(value = "/downLoadPdf", method = RequestMethod.POST)
public void downLoad(@RequestParam(value = "fileName") String fileName, HttpServletResponse response) throws IOException {
//输入处理流
InputStream inputStream = null;
//输出处理流
OutputStream outputStream = null;
long start = System.currentTimeMillis();
File file = new File(docBean.getFilePath() + fileName);
if (!file.exists()) {//如果文件不存在
logger.error("下载的文件不存在");
return;
}
try {
//定义文件输入流与输出流
inputStream = new BufferedInputStream(new FileInputStream(file));
outputStream = new BufferedOutputStream(response.getOutputStream());
logger.debug("设置response携带信息");
logger.debug("文件的大小:" + file.length());
response.reset();
// 设置在下载框默认显示的文件名
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//写明文件大小
response.addHeader("Content-Length", "" + file.length());
// 指明response的返回对象是文件流
response.setContentType("application/octet-stream");
//response.setContentType("multipart/form-data");
logger.debug("开始读取文件流");
//返回从该输入流中可以读取(或跳过)的字节数的估计值,而不会被下一次调用此输入流的方法阻塞
byte[] bytes = new byte[inputStream.available()];
//将pdf的内容写入bytes中
inputStream.read(bytes);
//将bytes中的内容写入
outputStream.write(bytes);
//刷新输出流,否则不会写出数据
outputStream.flush();
logger.debug("======文件下载处理完成==========");
} catch (FileNotFoundException e) {
logger.error("转换的pad文件未找到" + e.getMessage());
return;
} catch (IOException e) {
logger.error("文件读写异常" + e.getMessage());
return;
} finally {//关闭输入流、输出流
try {
if (inputStream != null) {
inputStream.close();
logger.debug("输入流关闭成功!");
}
if (outputStream != null) {
outputStream.close();
logger.debug("输出流关闭成功!");
}
long end = System.currentTimeMillis();
logger.debug("文件流处理时间" + (end - start));
} catch (IOException e) {
logger.error("关闭处理流出现异常" + e.getMessage());
return;
}
}
}
}
\ No newline at end of file
package cn.com.brilliance.doc.model;
import lombok.Data;
import java.io.Serializable;
@Data
public class TemplateData implements Serializable {
private String title;
private String date;
private String brNo;
private String amount;
private String no;
}
package cn.com.brilliance.doc.service;
import org.springframework.stereotype.Repository;
import java.io.IOException;
/**
* @Author weiguanying .
* @Date 2023/2/20
* @Description 文件预览接口
*/
@Repository
public interface PreviewService {
String preview(String fileName) throws IOException;
}
package cn.com.brilliance.doc.service;
import org.springframework.stereotype.Repository;
import java.util.Map;
@Repository
public interface WordTemplateService {
String docxTemplateToDocx(String templateName);
String poiCreateWord(Map<String, Object> paramMap);
}
package cn.com.brilliance.doc.service.impl;
import cn.com.brilliance.doc.config.DocBean;
import cn.com.brilliance.doc.service.PreviewService;
import cn.com.brilliance.doc.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
/**
* @Author weiguanying
* @Date 2023-02-20
* @Description 文件预览服务类 >> 将文件转为Base64输出给前端预览
*/
@Slf4j
@Service
public class PreviewServiceImpl implements PreviewService {
@Autowired
private DocBean docBean;
@Override
public String preview(String fileName) throws IOException {
File file = new File(docBean.getFilePath() + fileName);
return FileUtil.previewBean(file);
}
}
\ No newline at end of file
package cn.com.brilliance.doc.service.impl;
import cn.com.brilliance.doc.config.DocBean;
import cn.com.brilliance.doc.service.WordTemplateService;
import com.deepoove.poi.XWPFTemplate;
import fr.opensagres.xdocreport.document.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Map;
import java.util.UUID;
/**
* @author weiguanying
* @date 2023-02-20
* @description word-docx模板生成docx并返回文件名称
*/
@Service
public class WordTemplateServiceImpl implements WordTemplateService {
private static final Logger logger = LoggerFactory.getLogger(WordTemplateServiceImpl.class);
@Autowired
private DocBean docBean;
public String docxTemplateToDocx(String templateName) {
InputStream ins = null;
OutputStream out = null;
String templatesPath = docBean.getTemplatesPath() + templateName;
try {
//获取docx模板,模板存放路径 xxx.docx
ins = new FileInputStream(templatesPath);
//注册xdocreport实例并加载FreeMarker模板引擎
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(ins, TemplateEngineKind.Freemarker);
//创建xdocreport上下文对象,用于存放具体数据
IContext context = report.createContext();
//创建要替换的文本变量
context.put("name", "李梅");
context.put("age", "20");
context.put("school", "武汉大学");
String FileId = UUID.randomUUID().toString();
String newFileName = FileId + "-" + templateName;
//输出到本地目录
String filePath = docBean.getFilePath() + newFileName;
out = new FileOutputStream(filePath);
// 将前端参数写入文件输出流并保存为docx文件
report.process(context, out);
// 返回根据docx模板生产得docx文件
return newFileName;
} catch (Exception e) {
logger.info("生成word-docx发生异常", e);
} finally {
try {
if (ins != null) {
ins.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
logger.info("文件流关闭失败", e);
}
}
return null;
}
/**
*
* 基于poi-tl模板引擎生成docx模板文件为docx
* @param paramMap 模板文件替换参数
* @return
*/
public String poiCreateWord(Map<String, Object> paramMap) {
String templatePath = docBean.getTemplatesPath() + paramMap.get("templateName");
String targetPath = docBean.getFilePath() + paramMap.get("fileName");
// 读取模板渲染参数
XWPFTemplate template = XWPFTemplate.compile(templatePath).render(paramMap);
try {
// 将模板参数写入路径
template.writeToFile(targetPath);
template.close();
} catch (Exception e) {
e.printStackTrace();
logger.error("模板文件解析失败");
}
return targetPath;
}
}
package cn.com.brilliance.doc.utils;
import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@Slf4j
public class FileUtil {
/**
* @param file 转换文件名
* @return Byte数组
* @author weiguanying
* @date 2023-02-20
* 将file文件转换成Byte数组
*/
public static byte[] getBytesByFile(File file) throws IOException {
FileInputStream fis = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
try {
fis = new FileInputStream(file);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
byte[] data = bos.toByteArray();
return data;
} catch (Exception e) {
log.error("将文件转换成Byte数组失败", e);
} finally {
if (fis != null) {
fis.close();
}
bos.close();
}
return null;
}
/**
* @param file
* @return 将文件转换为byte[]数组后再转Base64字符串返回
* @throws IOException
* @author weiguanying
* @date 2023-02-20
*/
public static String previewBean(File file) throws IOException {
byte[] bytes = getBytesByFile(file);
String fileBase64 = Base64.encode(bytes);
return fileBase64;
}
}
\ No newline at end of file
package cn.com.brilliance.doc.utils;
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import lombok.extern.slf4j.Slf4j;
/**
* word:pdf To docx file util
*
* @author weiguanying
* Date 2023.02.19
*/
@Slf4j
public class PDFToWord {
public void PDFToWord(String filePath, String targetPath) {
// 代码运行开始时间
Long startTime = System.currentTimeMillis();
// 打印说明
String note = "程序执行时长";
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a sample PDF document
doc.loadFromFile(filePath);
//Convert PDF to Doc and save it to a specified path
//doc.saveToFile("d:\\ToPDF.doc", FileFormat.DOC);
//Convert PDF to Docx and save it to a specified path
doc.saveToFile(targetPath, FileFormat.DOCX);
doc.close();
// 代码运行结束时间
Long endTime = System.currentTimeMillis();
log.info("PDFToWord >> " + note + ":" + (endTime - startTime));
//System.out.println(note + ":" + (endTime - startTime));
}
}
package cn.com.brilliance.doc.utils;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
public class Result {
//是否成功")
private Boolean success;
//返回码")
private Integer code;
//返回消息")
private String message;
//返回数据")
private Map<String, Object> data = new HashMap<String, Object>();
//把构造方法私有
private Result() {
}
//成功静态方法
public static Result ok() {
Result r = new Result();
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS);
r.setMessage("成功");
return r;
}
//失败静态方法
public static Result error() {
Result r = new Result();
r.setSuccess(false);
r.setCode(ResultCode.ERROR);
r.setMessage("失败");
return r;
}
public Result success(Boolean success) {
this.setSuccess(success);
return this;
}
public Result message(String message) {
this.setMessage(message);
return this;
}
public Result code(Integer code) {
this.setCode(code);
return this;
}
public Result data(String key, Object value) {
this.data.put(key, value);
return this;
}
public Result data(Map<String, Object> map) {
this.setData(map);
return this;
}
}
package cn.com.brilliance.doc.utils;
public class ResultCode {
public static Integer SUCCESS = 20000; //成功
public static Integer ERROR = 20001; //失败
}
package cn.com.brilliance.doc.utils;
import com.spire.doc.Document;
import com.spire.doc.ToPdfParameterList;
import lombok.extern.slf4j.Slf4j;
/**
* word:docx To pdf file util
*
* @author weiguanying
* Date 2023.02.19
*/
@Slf4j
public class WordToPDF {
public void doxcTopdf(String filePath, String targetPath, String licenseKey) {
// if (licenseKey != null && !"".equals(licenseKey)) {
// com.spire.license.LicenseProvider.setLicenseKey("licenseKey");
// com.spire.license.LicenseProvider.loadLicense();
// }
// 代码运行开始时间
Long startTime = System.currentTimeMillis();
// 打印说明
String note = "程序执行时长";
Document doc = new Document();
// Load a sample Word document
doc.loadFromFile(filePath);
// Create a ToPdfParameterList instance
ToPdfParameterList ppl = new ToPdfParameterList();
// Embed all fonts in the PDF document
ppl.isEmbeddedAllFonts(true);
// Remove the hyperlinks and keep the character formats
ppl.setDisableLink(true);
// Set the output image quality as 40% of the original image. 80% is the default setting.
doc.setJPEGQuality(40);
// Save the document as PDF
doc.saveToFile(targetPath, ppl);
Long endTime = System.currentTimeMillis();
log.info("PDFToWord >> " + note + ":" + (endTime - startTime));
}
}
package cn.com.brilliance.doc.utils;
import com.deepoove.poi.XWPFTemplate;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class WordUtil {
public static void main(String[] args) throws IOException {
Map<String, Object> data = new HashMap();
data.put("title","1111");
data.put("date","2222");
data.put("brNo","3333");
data.put("amount","4444");
data.put("no","4444");
createWord("doc/src/main/resources/file/222.docx",
"doc/src/main/resources/file/",
"4444.docx", data);
}
/**
* @param templatePath word模板文件路径
* @param fileDir 生成的文件存放地址
* @param fileName 生成的文件名
* @param paramMap 参数集合
* @return 返回word生成的路径
* @author lsc
*/
public static String createWord(String templatePath, String fileDir, String fileName, Map<String, Object> paramMap) throws IOException {
File dir = new File(fileDir);
if (!dir.exists()) {
dir.mkdirs();
}
String filePath = fileDir + "\\" + fileName;
//XWPFDocument doc = new XWPFDocument(new FileInputStream("src/main/resources/file/222.docx"));
// 读取模板渲染参数
XWPFTemplate template = XWPFTemplate.compile(templatePath).render(paramMap);
try {
// 将模板参数写入路径
template.writeToFile(filePath);
template.close();
} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}
}
# 应用名称
spring:
application:
name: doc
# 服务端口
server:
port: 8081
# 面函服务工程文件扫描路径
faceLetter:
filePath: doc\\src\\main\\resources\\file\\ # 下载文件路径
templatesPath: doc\\src\\main\\resources\\templates\\ # 模板文件路径
spire:
key: cYF3RgYqIEu1ywEAXY/dDnq7WM/SMA0jCcsSknwdlLyIP6dUJ+M0msjBAiMEzW1LJrZNEL28dzCRrwF2GSgtQGbz5nh+mp1HpAp4DZYF4CRDsNo4N28MuwQuWDffKi2UT+FgYr1nr4GH7iuCCak0Wy29q58MV5qr/yhSPxt2fjl276k1FfROuZUyxT8C4czau/TIpr19M/XQvbOLNvkVqneTUyOMA17kdtEbXvkoVGqtXS//wCgdGGT1UVqFHULK0pvWAdUjU+3dZjE7cEr2Iw33sES7Q1M+7MPSIvg/V0qho46VHT5hc/PtFeNDD4PQ/HeCnIeZ477PwIkyMKf6T4KCIPI77rkeNWBhsdYfnQj1LBADrwUYRPJ86S5vkIiOIRna19KsmvgQrO/GNTodtZ6rSXHNqoBRZpcF3yyaArLwBsCqxk0XRDFYLeCX005A6tc3V8Z//1KOmay5N74lSG9LH4gxt5sm9BZ8cWvq5KVR3EOaeMZX4ZcIm6PCLlhbVOwGFwAIuyIw3T7BOVUiPbSsD/pY8NB9ogQWiKI0rhLEs+1IBfP9uGIALcywR6SEoTdbKMOnekzzYi35iwjrEdEeA9LJDfynh3qX5CjHCuCVW2sHe60w3XIM2cYEpGdrA+odYvbHFP3q7Ot7r9Iovq0dmfEpkGMdHYmlSZDCEICeXPrjs8kUPv55oWzlZH1dmpah+ATAhH6I8JZ0lEzepAQ0Vu3lxyyb1ulGrdOcVZ4BP5xw/Baz24xW7WVL7Cb6bRdlX6HCh6yUHsw7yjr4+k6+Qp0r5qlf7XkVL0BajAzkkdNK1lCVUA0vhMm5FtodULn0VI5odS4DMtGeoqDbdOAusAikvwMCEdCdgbUKMppDXmmNCClb4NxGBvvmjRXOT0vKTatYGGQNE7q9eNKWkStm9Lp+3UtooVg9zJy5vRYiwjWcH4E4iTfqnRTeWsxyWk4KTkUlXYsG8C7at0CalM9O3efw7gkFeibx4tFgZeZPkBz+z9GsotGiFjtAcrtJjtB0zAF7JcDD/oVkPYAZo6yg1h6dziMyZLfcvAyyMztrRd0Uf0vqqstRWYB9hLnS0cLHUo4Aic5i2a17QCkxMxFTNa4IIKXcEwNJXHjWcZ+ABVFSPRAn3sjpfG623r6iNOdPRBnmjcEnbcZJ1YHsvw6xu3/KMx+5brJDWcZid7UmmYkquQ5v3P6On9b8TMYhVr7eA7jP7H619UmZILwBt0AmY2G4/vKgMV8CYZqWw5HpmTBP6s6ZI92dSSMxPgtdFbcURJqGSB/6ExDbl2JCXYIPtY4qyQl7VU/sjv20z/T/qNxwTLWjXiusr7bFRxuTLHJjsOi2/AVbrDk+0v2uLjVrBRdhsBW+qTqpmJNCB63AGpdiScBNc2FSr+izpAJA0DXLtNVKDA3s2nybNS9XHw==
<?xml version="1.0" encoding="utf-8"?>
<License xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Key="cYF3RgYqIEu1ywEAXY/dDnq7WM/SMA0jCcsSknwdlLyIP6dUJ+M0msjBAiMEzW1LJrZNEL28dzCRrwF2GSgtQGbz5nh+mp1HpAp4DZYF4CRDsNo4N28MuwQuWDffKi2UT+FgYr1nr4GH7iuCCak0Wy29q58MV5qr/yhSPxt2fjl276k1FfROuZUyxT8C4czau/TIpr19M/XQvbOLNvkVqneTUyOMA17kdtEbXvkoVGqtXS//wCgdGGT1UVqFHULK0pvWAdUjU+3dZjE7cEr2Iw33sES7Q1M+7MPSIvg/V0qho46VHT5hc/PtFeNDD4PQ/HeCnIeZ477PwIkyMKf6T4KCIPI77rkeNWBhsdYfnQj1LBADrwUYRPJ86S5vkIiOIRna19KsmvgQrO/GNTodtZ6rSXHNqoBRZpcF3yyaArLwBsCqxk0XRDFYLeCX005A6tc3V8Z//1KOmay5N74lSG9LH4gxt5sm9BZ8cWvq5KVR3EOaeMZX4ZcIm6PCLlhbVOwGFwAIuyIw3T7BOVUiPbSsD/pY8NB9ogQWiKI0rhLEs+1IBfP9uGIALcywR6SEoTdbKMOnekzzYi35iwjrEdEeA9LJDfynh3qX5CjHCuCVW2sHe60w3XIM2cYEpGdrA+odYvbHFP3q7Ot7r9Iovq0dmfEpkGMdHYmlSZDCEICeXPrjs8kUPv55oWzlZH1dmpah+ATAhH6I8JZ0lEzepAQ0Vu3lxyyb1ulGrdOcVZ4BP5xw/Baz24xW7WVL7Cb6bRdlX6HCh6yUHsw7yjr4+k6+Qp0r5qlf7XkVL0BajAzkkdNK1lCVUA0vhMm5FtodULn0VI5odS4DMtGeoqDbdOAusAikvwMCEdCdgbUKMppDXmmNCClb4NxGBvvmjRXOT0vKTatYGGQNE7q9eNKWkStm9Lp+3UtooVg9zJy5vRYiwjWcH4E4iTfqnRTeWsxyWk4KTkUlXYsG8C7at0CalM9O3efw7gkFeibx4tFgZeZPkBz+z9GsotGiFjtAcrtJjtB0zAF7JcDD/oVkPYAZo6yg1h6dziMyZLfcvAyyMztrRd0Uf0vqqstRWYB9hLnS0cLHUo4Aic5i2a17QCkxMxFTNa4IIKXcEwNJXHjWcZ+ABVFSPRAn3sjpfG623r6iNOdPRBnmjcEnbcZJ1YHsvw6xu3/KMx+5brJDWcZid7UmmYkquQ5v3P6On9b8TMYhVr7eA7jP7H619UmZILwBt0AmY2G4/vKgMV8CYZqWw5HpmTBP6s6ZI92dSSMxPgtdFbcURJqGSB/6ExDbl2JCXYIPtY4qyQl7VU/sjv20z/T/qNxwTLWjXiusr7bFRxuTLHJjsOi2/AVbrDk+0v2uLjVrBRdhsBW+qTqpmJNCB63AGpdiScBNc2FSr+izpAJA0DXLtNVKDA3s2nybNS9XHw==" Version="1.3">
<Type>Temporary</Type>
<Username>傅凯</Username>
<Email>303002971@qq.com</Email>
<LicensedDate>2023-02-16T00:00:00Z</LicensedDate>
<ExpiredDate>2023-03-16T00:00:00Z</ExpiredDate>
<Products>
<Product>
<Name>Spire.Doc for JAVA</Name>
<Version>11.1</Version>
<Subscription>
<NumberOfPermittedDeveloper>50</NumberOfPermittedDeveloper>
<NumberOfPermittedSite>2147483647</NumberOfPermittedSite>
</Subscription>
</Product>
</Products>
<Issuer>
<Name>e-iceblue</Name>
<Email>sales@e-iceblue.com</Email>
<Url>http://www.e-iceblue.com</Url>
</Issuer>
</License>
\ No newline at end of file
package cn.com.brilliance.doc;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DocApplicationTests {
@Test
void contextLoads() {
}
}
package cn.com.brilliance.doc.test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Test01 {
public static void main(String[] args) throws IOException {
String filePath = "doc\\src\\main\\resources\\file\\555.docx";
//获取上传文件输入流,便于文件内容读写操作
InputStream inputStream = new FileInputStream(filePath);
inputStream.close();
//subString();
}
public static String subString() {
String [] str = {"Lb", "Amount", "to", "Be", "Paid", "8", "127", "-1", "0"}
;
String [] newStr = new String[4];
for (int i = 0; i < 4; i++) {
newStr[i] = str[str.length - (4-i)];
}
System.out.println(newStr.toString());
String content = str.toString();//"\u001FDetails of Calculation\u001F";
String value = content.substring(content.indexOf("\u001F") + 1, content.lastIndexOf("\u001F"));
System.out.println(value);
return value;
}
}
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar
This diff is collapsed. Click to expand it.
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %*
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% ^
%JVM_CONFIG_MAVEN_PROPS% ^
%MAVEN_OPTS% ^
%MAVEN_DEBUG_OPTS% ^
-classpath %WRAPPER_JAR% ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%"=="on" pause
if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE%
cmd /C exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.11</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.com.brilliance</groupId>
<artifactId>dsp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>dsp</name>
<description>dsp</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package cn.com.brilliance.dsp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DspApplication {
public static void main(String[] args) {
SpringApplication.run(DspApplication.class, args);
}
}
package cn.com.brilliance.dsp.config;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* @Author weiguanying
* @Date 2023-02-20
* @Description configClass
*/
@Configuration
@PropertySource("classpath:application.yml")
@Getter
public class DocBean {
@Value("${faceLetter.filePath}")
private String filePath;
@Value("${faceLetter.templatesPath}")
private String templatesPath;
}
package cn.com.brilliance.dsp.controller;
import cn.com.brilliance.dsp.config.DocBean;
import cn.com.brilliance.dsp.model.*;
import cn.com.brilliance.dsp.service.FrameService;
import cn.com.brilliance.dsp.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.util.*;
@RestController
@Slf4j
@RequestMapping("/api")
public class ParseDspFileController {
private static final Logger logger = LoggerFactory.getLogger(ParseDspFileController.class);
private static final String KEYONE = "FrameField";
private static final String KEYTWO = "FieldValue";
private static final String KEYTHREE = "FramePanel";
private static final String KEYFOUR = "GridValue";
private static final String KEYFIVE = "GridLists";
private static final String KEYSIX = "Label";
private static final String KEYSEVEN = "Grid";
@Autowired
private DocBean docBean;
@Autowired
private FrameService frameService;
@PostMapping("/dspfile")
public <T> Result dspParse(@RequestParam(value = "file") String fileName) throws Exception {
//获取上传文件名称
//String fileName = file.getOriginalFilename();
//获取上传文件类型
//String contentType = file.getContentType();
String filePath = docBean.getFilePath() + fileName;
String fileType = fileName.substring(fileName.indexOf(".") + 1);
if (!"DSP".equals(fileType)) {
logger.error("文件格式错误!");
return Result.error().message("文件格式错误!");
}
//获取上传文件输入流,便于文件内容读写操作
FileInputStream inputStream = new FileInputStream(filePath);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GB2312");
BufferedReader reader = new BufferedReader(inputStreamReader);
// 解析文件内容并返回
List<Panel> panelList = new ArrayList<>();
Panel panel = new Panel();
List<Table> tableList = null;
FrameField frameField = null;
List<T> list = null;
String prop = null;
List<String> tableValues =null;
Table table1 = null;
List<String> props = null;
List<String> widths = null;
Grid grid = null ;
List<GridValue> gridValues = null ;
try {
String line;
while ((line = reader.readLine()) != null) {
// 读取到的结果
HashMap<String, Object> result = frameService.printEibsElement(line);
if (result != null) {
// 多个panel组装
if (result.containsKey(KEYTHREE)) {
panel = (Panel) result.get(KEYTHREE);
panelList.add(panel);
list = new ArrayList<>();
}
// 多个field组装
if (result.containsKey(KEYONE)) {
frameField = (FrameField) result.get(KEYONE);
list.add((T) frameField);
}
// 多个value组装到上一行的field上
if (result.containsKey(KEYTWO)) {
FrameField frameValue = (FrameField) result.get(KEYTWO);
FrameField ff = (FrameField) list.get(list.size() - 1);
ff.setValue(ff.getValue() != null ? ff.getValue() + frameValue.getValue() : frameValue.getValue());
list.remove(list.get(list.size() - 1));
ff.setValue(ff.getValue().replaceAll("\u001F", ""));
list.add((T) ff);
panel.setList(list);
}
if (result.containsKey(KEYSIX)) {
Label label = (Label) result.get(KEYSIX);
label.setViewType("Label");
list.add((T) label);
panel.setList(list);
}
// if (result.containsKey(KEYSEVEN)) {
// tableList = new ArrayList<>();
// table1 = new Table();
// props = new ArrayList<>();
// widths = new ArrayList<>();
// tableValues = new ArrayList<>();
// grid = new Grid();
// }
//
// if (result.containsKey(KEYFIVE)) {
// GridLists gridLists = (GridLists) result.get(KEYFIVE);
// widths.add(gridLists.getWidth());
// frameField.setWidths(widths);
// }
//
// if (result.containsKey(KEYFOUR)) {
// GridValue gridValue = (GridValue) result.get(KEYFOUR);
// if ("0".equals(gridValue.getRow())) {
// prop = gridValue.getValue();
// props.add(prop);
// frameField.setProps(props);
// } else {
// // if (Integer.parseInt(gridValue.getRow()) < Integer.parseInt(grid.getRows()) - 1 ){
// tableValues.add(gridValue.getValue());
// // } else {
// // tableValues.add(gridValue.getValue() + "&&");
// // }
// frameField.setTableValues(tableValues);
// }
// FrameField ff = (FrameField) list.get(list.size() - 1);
// list.remove(list.get(list.size() - 1));
// list.add((T) ff);
// panel.setList(list);
// }
// if (result.containsKey(KEYSEVEN)) {
// tableList = new ArrayList<>();
// table1 = new Table();
// props = new ArrayList<>();
// widths = new ArrayList<>();
// tableValues = new ArrayList<>();
//
//
// }
//
// if (result.containsKey(KEYFIVE)) {
// GridLists gridLists = (GridLists) result.get(KEYFIVE);
// table1 = new Table();
// table1.setWidth(gridLists.getWidth());
// tableList.add(table1);
// }
//
// if (result.containsKey(KEYFOUR)) {
// GridValue gridValue = (GridValue) result.get(KEYFOUR);
// int i = Integer.parseInt(gridValue.getRow());
// int j = Integer.parseInt(gridValue.getColumn());
// if (i == 0) {
// Table table2 = tableList.get(i);
// table2.setProp(gridValue.getValue());
// tableList.remove(j);
// tableList.add(j,table2);
// } else {
// Table table2 = tableList.get(i);
// //table2.setProp(gridValue.getValue());
// tableValues.add(gridValue.getValue());
// table2.setValues(tableValues);
// }
// frameField.setTableList(tableList);
// }
if (result.containsKey(KEYSEVEN)) {
Grid grid1 = (Grid) result.get(KEYSEVEN);
widths = new ArrayList<>();
gridValues = new ArrayList<>();
}
if (result.containsKey(KEYFIVE)) {
GridLists gridLists = (GridLists) result.get(KEYFIVE);
widths.add(gridLists.getWidth());
}
if (result.containsKey(KEYFOUR)) {
GridValue gridValue = (GridValue) result.get(KEYFOUR);
gridValue.setWidth(widths.get(Integer.parseInt(gridValue.getColumn())));
gridValues.add(gridValue);
FrameField ff = (FrameField) list.get(list.size() - 1);
ff.setGridValues(gridValues);
list.remove(list.get(list.size() - 1));
list.add((T) ff);
panel.setList(list);
}
}
}
} catch (Exception e) {
logger.error("ParseDspFileController.dspParse 处理DSP文件解析失败!");
return Result.error().message("DSP文件解析失败!");
}
// 关闭流对象
if (inputStream != null) {
inputStream.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (reader != null) {
reader.close();
}
Object o = panelList;
Map<String, Object> map = new HashMap<>();
map.put("panelLists", o);
return Result.ok().data(map);
}
}
package cn.com.brilliance.dsp.model;
import lombok.Data;
import java.util.List;
@Data
public class FrameField {
private String left;
private String top;
private String width;
private String height;
private String visible;
private String readonly;
private String mandatory;
private String checkvalue;
private String viewType;
private String enabled;
private String value;
private List<Table> tableList;
private List<String> widths;
private List<String> props;
private List<String> tableValues;
private Grid grid;
private List<GridLists> gridLists;
private List<GridValue> gridValues;
}
package cn.com.brilliance.dsp.model;
import lombok.Data;
@Data
public class Grid {
private String rows;
private String columns;
}
package cn.com.brilliance.dsp.model;
import lombok.Data;
@Data
public class GridLists {
private String column;
private String width;
}
package cn.com.brilliance.dsp.model;
import lombok.Data;
@Data
public class GridValue {
private String width;
private String row;
private String column;
private String value;
private String isRedLine;
private String isButton;
}
package cn.com.brilliance.dsp.model;
import lombok.Data;
@Data
public class Label {
private String value;
private String left;
private String top;
private String width;
private String height;
private String viewType ;
}
package cn.com.brilliance.dsp.model;
import lombok.Data;
import java.util.List;
@Data
public class Panel<T> {
private String name;
private String width;
private String height;
private List<T> list ;
}
package cn.com.brilliance.dsp.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Table {
private String prop;
private String width;
private List<String> values;
}
package cn.com.brilliance.dsp.service;
import org.springframework.stereotype.Repository;
import java.util.HashMap;
/**
* @Author weiguanying .
* @Date 2023/2/20
* @Description dsp file parse interface.
*/
@Repository
public interface FrameService {
HashMap<String,Object> printEibsElement(String content);
}
package cn.com.brilliance.dsp.service.impl;
import cn.com.brilliance.dsp.model.*;
import cn.com.brilliance.dsp.service.FrameService;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
/**
* @author weiguanying .
* @date 2023/2/20
* @description dsp file parse service.
*/
@Service
public class FrameServiceImpl implements FrameService {
public static class KV {
int index;
public KV(StringBuffer components, int index, List<StringBuffer> fieldValues) {
this.index = index;
this.components = components;
this.fieldValues = fieldValues;
}
StringBuffer components;
List<StringBuffer> fieldValues;
public int getIndex() {
return index;
}
public StringBuffer getComponents() {
return components;
}
public List<StringBuffer> getFieldValues() {
return fieldValues;
}
}
/**
* 获取数组下标
*
* @param lines
* @param pos
* @return
*/
protected String getLineField(String[] lines, int pos) {
if (lines.length >= pos + 1) {
return lines[pos];
}
return "";
}
/**
* 字符串拆分成数组
*
* @param line
* @return
*/
public static String[] splitLine(String line) {
line = line.trim();// 原处理是trimStart
return line.split("(?<!(\\{)[^}]{0,1000})\\s+(?=[^}]*(\\{|$))");
}
/**
* 根据特定字符串截取名称
*
* @param line 一行字符串数据
* @return "\u001F" 中间的字符串
* @author weiguanying
*/
public static String valueString(String line) {
String value = line.substring(line.indexOf("\u001F") + 1, line.lastIndexOf("\u001F"));
return value;
}
/**
* 获取 String [] 最后几个数组
*
* @param str
* @param total
* @return
* @author weiguanying
*/
public static String[] subStr(String[] str, int total) {
String[] newStr = new String[total];
for (int i = 0; i < total; i++) {
newStr[i] = str[str.length - (total - i)];
}
return newStr;
}
@Override
public HashMap<String, Object> printEibsElement(String content) {
String[] fields;
StringBuffer writeLine = new StringBuffer(""); // 最终返回字符串
fields = splitLine(content);
String fieldName = getLineField(fields, 0).toLowerCase().trim();
String fieldType = getLineField(fields, 1);
HashMap<String, Object> map = new HashMap<>();
if ("ff".equals(fieldName)) {
if (fieldType.equals("16") || fieldType.equals("5")) {
}// GridView暂时不处理
String field = "field";
String fieldPositionX = "";
String fieldPositionY = "";
String fieldWidth = "0";
String fieldHeight = "0";
String fieldVisible = ""; // 1-visible
String fieldReadonly = ""; // 1-readonly
String fieldMandatory = ""; // 1-mandatory
String fieldCheckValue = ""; // 1-checkvalue
String fieldIndependent = ""; // 1-independent
String fieldTabGroup = ""; // 1-tabgroup
String fieldShowKey = ""; // 1-showkey
fieldPositionX = getLineField(fields, 2);
fieldPositionY = getLineField(fields, 3);
fieldWidth = getLineField(fields, 4);
fieldHeight = getLineField(fields, 5);
fieldVisible = getLineField(fields, 6); // 1-visible
fieldReadonly = getLineField(fields, 7); // 1-readonly
fieldMandatory = getLineField(fields, 8); // 1-mandatory
fieldCheckValue = getLineField(fields, 9); // 1-
if (("1").equals(fieldType)) {
fieldCheckValue = getLineField(fields, 11); // 1-
}
fieldIndependent = getLineField(fields, 10); // 1-independent
fieldTabGroup = getLineField(fields, 11); // 1-tabgroup
fieldShowKey = getLineField(fields, 12); // 1-showkey
FrameField frameField = new FrameField();
frameField.setLeft(fieldPositionX);
frameField.setTop(fieldPositionY);
frameField.setWidth(fieldWidth);
frameField.setHeight(fieldHeight);
frameField.setVisible(fieldVisible);
frameField.setReadonly(fieldReadonly);
frameField.setMandatory(fieldMandatory);
frameField.setCheckvalue(fieldCheckValue);
switch (fieldType) {
case "1": {
frameField.setViewType("Block");
break;
}
case "2": {
frameField.setViewType("Combobox");
break;
}
case "3": {
frameField.setViewType("Checkbox");
break;
}
case "0": {
frameField.setViewType("Input");
break;
}
// case "5": {
// frameField.setViewType("Label");
// break;
// }
case "6": {
frameField.setViewType("Button");
break;
}
case "7": {
frameField.setViewType("Date");
break;
}
case "8": {
frameField.setViewType("Amount");
break;
}
case "10": {
frameField.setViewType("Table");
break;
}
case "11": {
frameField.setViewType("Block");
break;
}
case "14": {
frameField.setViewType("Password");
break;
}
case "17": {
frameField.setViewType("Composite");
break;
}
}
if (fieldReadonly.equals("1")) {
frameField.setEnabled("false");
}
if (fieldMandatory.equals("1")) {
frameField.setEnabled("true");
}
map.put("FrameField", frameField);
} else if ("lb".equals(fieldName)) {
Label label = new Label();
String fieldText = valueString(content);// getLineField(fields, 1).trim();
String fieldWidth = "75";
String fieldHeight = "22";
String[] newStr = subStr(fields, 4);
String fieldPositionX = getLineField(newStr, 0);
String fieldPositionY = getLineField(newStr, 1);
//String fieldHeight = getLineField(newStr, 2);
//String fieldWidth = getLineField(newStr, 3);
label.setHeight(fieldHeight);
label.setWidth(fieldWidth);
label.setValue(fieldText);
label.setLeft(fieldPositionX);
label.setTop(fieldPositionY);
map.put("Label", label);
} else if ("fp".equals(fieldName)) {
String[] newStr = subStr(fields, 4);
String fieldText = valueString(content);// getLineField(fields, 1).trim();
String fieldPositionX = getLineField(newStr, 0);
String fieldPositionY = getLineField(newStr, 1);
String fieldHeight = getLineField(newStr, 2);
String fieldWidth = getLineField(newStr, 3);
Panel panel = new Panel();
panel.setName(fieldText);
panel.setWidth(fieldWidth);
panel.setHeight(fieldHeight);
map.put("FramePanel", panel);
} else if ("grid".equals(fieldName)) {
Grid grid = new Grid();
grid.setRows(getLineField(fields, 1));
grid.setColumns(getLineField(fields, 2));
map.put("Grid", grid);
} else if ("gc".equals(fieldName)) {
GridLists lists = new GridLists();
lists.setColumn(getLineField(fields, 1));
lists.setWidth(getLineField(fields, 2));
map.put("GridLists", lists);
} else if ("gv".equals(fieldName)) {
GridValue gridValue = new GridValue();
String fieldText = valueString(content);// getLineField(fields, 1).trim();
gridValue.setValue(fieldText);
gridValue.setColumn(getLineField(fields, 2));
gridValue.setRow(getLineField(fields, 1));
String[] newStr = subStr(fields, 6);
gridValue.setIsRedLine("0".equals(getLineField(newStr, 4)) ? "Y" : "N");
gridValue.setIsButton("6".equals(getLineField(newStr, 0)) ? "Y" : "N");
map.put("GridValue", gridValue);
return map;
} else if ("va".equals(fieldName)) {
FrameField frameField = new FrameField();
//frameField.setValue(getLineField(fields, 1));
frameField.setValue(content.replaceFirst("Va", ""));
map.put("FieldValue", frameField);
}
return map;
}
}
package cn.com.brilliance.dsp.utils;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
public class Result {
//是否成功")
private Boolean success;
//返回码")
private Integer code;
//返回消息")
private String message;
//返回数据")
private Map<String, Object> data = new HashMap<String, Object>();
//把构造方法私有
private Result() {
}
//成功静态方法
public static Result ok() {
Result r = new Result();
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS);
r.setMessage("成功");
return r;
}
//失败静态方法
public static Result error() {
Result r = new Result();
r.setSuccess(false);
r.setCode(ResultCode.ERROR);
r.setMessage("失败");
return r;
}
public Result success(Boolean success) {
this.setSuccess(success);
return this;
}
public Result message(String message) {
this.setMessage(message);
return this;
}
public Result code(Integer code) {
this.setCode(code);
return this;
}
public Result data(String key, Object value) {
this.data.put(key, value);
return this;
}
public Result data(Map<String, Object> map) {
this.setData(map);
return this;
}
}
package cn.com.brilliance.dsp.utils;
public class ResultCode {
public static Integer SUCCESS = 20000; //成功
public static Integer ERROR = 20001; //失败
}
# 应用名称
spring:
application:
name: dsp
# 服务端口
server:
port: 8082
# 面函服务工程文件扫描路径
faceLetter:
filePath: dsp\\src\\main\\resources\\file\\ # 下载文件路径 src/main/resources/file/
templatesPath: dsp\\src\\main\\resources\\templates\\ # 模板文件路径
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment