PHP富文本转word,ueditor富文本保存或下载word

UEditor官网下载:完整源码,JSP版本

创建springboot项目

①将完整源码中的/jsp/src目录下的文件夹拷贝至项目的src目录下;

②将JSP版本下的所有文件拷贝至项目的resources/static下;

③将JSP版本下的jsp/config.json文件拷贝至resources目录;

④将JSP版本下的index.html拷贝到resources/templates下,并修改该页面所引用的css/js路径;

引用依赖

1.8

3.17

org.springframework.boot

spring-boot-starter-thymeleaf

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-configuration-processor

true

org.springframework.boot

spring-boot-devtools

true

true

org.json

json

20160810

commons-fileupload

commons-fileupload

1.3.3

commons-codec

commons-codec

1.11

org.apache.poi

poi

${poi.version}

org.apache.poi

poi-scratchpad

${poi.version}

org.apache.poi

poi-ooxml

${poi.version}

org.apache.poi

poi-ooxml-schemas

${poi.version}

org.apache.poi

ooxml-schemas

1.4

org.apache.commons

commons-lang3

3.7

fr.opensagres.xdocreport

xdocreport

2.0.1

net.sf.json-lib

json-lib

2.4

jdk15

org.springframework.boot

spring-boot-starter-test

test

org.junit.vintage

junit-vintage-engine

编辑application.yml文件

server:

port: 8890

#上传图片大小设置

max-http-header-size: 102400

#文件上传保存的路径

web:

file-path: E:\Example

spring:

mvc:

static-path-pattern: /**

resources:

static-locations: classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/, file:${web.file-path}

修改resources/config.json文件

// 增加代码,表示上传路径

"basePath": "E:/Example/"

// 将

"imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",

// 修改为下面这行,这是上传的图片所保存的目录

"imagePathFormat": "/upload/{time}{rand:6}",

修改resources/static/ueditor/ueditor.config.js文件

serverUrl: URL + "jsp/controller.jsp"

// 修改为

serverUrl: "/config"

编写控制器

// 页面显示

@RequestMapping("/")

public String index() {

return "index";

}

// 映射config.json

@RequestMapping("/config")

public void config(HttpServletRequest request, HttpServletResponse response) {

response.setContentType("application/json");

String rootPath = request.getSession().getServletContext().getRealPath("/");

System.out.println(rootPath);

try {

String exec = new ActionEnter(request, rootPath).exec();

PrintWriter writer = response.getWriter();

writer.write(exec);

writer.flush();

writer.close();

} catch (IOException e) {

e.printStackTrace();

}

}

修改UEditor相关源码文件

// **修改ConfigManeger类的getConfigPath()方法:

private String getConfigPath () {

// return this.parentPath + File.separator + ConfigManager.configFileName;

// ————————————替换修改

try{

//获取classpath下的config.json路径

return this.getClass().getClassLoader().getResource("config.json").toURI().getPath();

}catch (URISyntaxException e){

return null;

}

// ————————————————————————

}

// **修改ConfigManager类的getConfig()方法:

// ————————增加的代码————————

conf.put( "basePath", this.jsonConfig.getString("basePath") );

// ————————————————————————

conf.put( "savePath", savePath );

conf.put( "rootPath", this.rootPath );

// **修改BinaryUploader类**

// 注释该代码:

FileItemStream fileStream = null;

boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;

// 注释该代码:

ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

if ( isAjaxUpload ) {

upload.setHeaderEncoding( "UTF-8" );

}

// 注释该代码:

FileItemIterator iterator = upload.getItemIterator(request);

while (iterator.hasNext()) {

fileStream = iterator.next();

if (!fileStream.isFormField())

break;

fileStream = null;

}

if (fileStream == null) {

return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);

}

// 将

String originFileName = fileStream.getName();

// 修改为:

String originFileName = multipartFile.getOriginalFilename();

// 将

String physicalPath = (String) conf.get("rootPath") + savePath;

// 修改为:

String basePath = (String) conf.get("basePath");

String physicalPath = basePath + savePath;

// 将

InputStream is = fileStream.openStream();

// 修改为:

InputStream is = multipartFile.getInputStream();

编写ConfigUtils工具,意在获取路径

// 获取config.json文件中的image的上传路径

public static String imagePath() {

ClassPathResource config = new ClassPathResource("config.json");

try {

File file = config.getFile();

String input = FileUtils.readFileToString(file, "UTF-8");

JSONObject jsonObject = JSONObject.fromObject(input);

if (jsonObject != null) {

return jsonObject.get("imagePathFormat").toString();

}

} catch (Exception e) {

e.getStackTrace();

}

return null;

}

// 获取yml中自定义上传的根路径,届时将跟image路径替换拼接起来,word中的图片才能显示。

public static String filePath() {

YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();

yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));

Properties properties = yamlMapFactoryBean.getObject();

assert properties != null;

return properties.getProperty("web.file-path");

}

编写POIUtils工具,输出保存word

/**

* 在Config.js中的图片路径,对应替换

*/

private static String IMAGE_PATH = Objects.requireNonNull(ConfigUtils.imagePath()).replace("{time}{rand:6}", ""); // 上传的图片路径

private static String FILE_PATH = ConfigUtils.filePath(); // 上传路径

/**

* ueditor导出word到浏览器下载

*

* home.php?mod=space&uid=952169 request  request

* @param response response

* @param content  内容

* @param fileName 文件名

* @param suffix   拓展名

*/

public static void exportWordToBrowser(HttpServletRequest request,

HttpServletResponse response,

String content,

String fileName,

String suffix) {

try {

// 传入的图片路径,未有头路径,需要替换后保存的word才能显示图片。

String str = content.replace(IMAGE_PATH, FILE_PATH.concat(IMAGE_PATH));

StringBuilder sbf = new StringBuilder();

sbf.append("

"); //缺失的首标签

sbf.append(str); // 富文本内容

sbf.append(""); // 缺失的尾标签

byte[] b = sbf.toString().getBytes("GBK");  // 这里是必须要设置编码的,不然导出中文就会乱码。

ByteArrayInputStream bais = new ByteArrayInputStream(b); // 将字节数组包装到流中

POIFSFileSystem poifs = new POIFSFileSystem();

DirectoryEntry directory = poifs.getRoot();

DocumentEntry documentEntry = directory.createDocument("WordDocument", bais); // 该步骤不可省略,否则会出现乱码。

// 输出文件

request.setCharacterEncoding("utf-8");

response.setContentType("application/msword"); // 导出word格式

response.addHeader("Content-Disposition", "attachment;filename=" +

new String(fileName.getBytes("GB2312"), "iso8859-1").concat(".").concat(suffix));

ServletOutputStream sos = response.getOutputStream();

poifs.writeFilesystem(sos);

bais.close();

sos.close();

poifs.close();

} catch (Exception e) {

log.error(e.getMessage(), e);

}

}

/**

* ueditor保存word至硬盘

*

* @param content  内容

* @param savePath 保存路径

* @param fileName 完整文件名

*/

public static void exportWordToDisk(String content, String savePath, String fileName) {

try {

// 传入的图片路径,未有头路径,需要替换后保存的word才能显示图片。

String str = content.replace(IMAGE_PATH, FILE_PATH.concat(IMAGE_PATH));

StringBuilder sbf = new StringBuilder();

sbf.append("

"); //缺失的首标签

sbf.append(str); // 富文本内容

sbf.append(""); // 缺失的尾标签

byte[] b = sbf.toString().getBytes("GBK");

ByteArrayInputStream bais = new ByteArrayInputStream(b);

POIFSFileSystem poifs = new POIFSFileSystem();

DirectoryEntry directory = poifs.getRoot();

DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);

if (!new File(savePath).isDirectory())

new File(savePath).mkdir();

FileOutputStream os = new FileOutputStream(savePath.concat(fileName));

// 输出文件

poifs.writeFilesystem(os);

bais.close();

os.close();

} catch (Exception e) {

log.error(e.getMessage(), e);

}

}

编写控制器方法

/**

* 导出成word浏览器下载

* @param request

* @param response

* @param content

*/

@RequestMapping("/exportWordToBrowser")

public void exportWordToBrowser(HttpServletRequest request, HttpServletResponse response, @RequestParam("content") String content) {

POIUtils.exportWordToBrowser(request, response, content,"demo", "docx");

}

/**

* 导出成word保存到硬盘

* @param content

* @return

*/

@RequestMapping("/exportWordToDisk")

@ResponseBody

public R exportWordToDisk(@RequestParam("content") String content) {

try {

String savePath = ConfigUtils.filePath().concat("/file/");

POIUtils.exportWordToDisk(content, savePath, "save.docx");

return R.ok();

} catch (Exception e) {

return R.error();

}

}

修改index.html方法

// 导出word至硬盘

function saveWord() {

$.ajax({

url: '/exportWordToDisk',

data: {

content: UE.getEditor('editor').getContent()

},

headers: {

'Content-Type': 'application/json;charset=utf8'

},

success: function (res) {

if (res.code === 0) {

alert(res.msg)

}

}

})

}

// 导出word至浏览器;使用form表单提交内容更多

function downloadWord() {

var url = "/exportWordToBrowser";

var form = $("

").attr("action", url).attr("method", "post");

form.append($("").attr("type", "hidden").attr("name", "content").attr("value", UE.getEditor('editor').getContent()));

form.appendTo('body').submit().remove();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值