导出工具
html-docx-js-typescript
file-saver
踩坑经历及原因
使用SunEditor编辑页面,然后要将编辑过的页面导出为word文件。
用sunEditor插件的getContent方法,获取的页面html标签的字符串中,没有带标签上的style属性。
1、没有边框解决办法
使用获取dom元素的innerHTML可以拿到带style标签的html文本字符串,这时只要你在style中设置了边框,导出的表格就有边框了。
import { saveAs } from 'file-saver';
import { asBlob } from 'html-docx-js-typescript'
const innerHtmlStr = document.querySelector('.sun-editor-editable')?.innerHTML;
const htmlStr = `
<!DOCTYPE html>
<html lang="en">
<body style="font-family:方正仿宋_GBK;mso-ascii-font-family:'Times New Roman';">
${innerHtmlStr }
</body>
</html>
`;
asBlob(htmlStr,{ orientation: 'landscape', margins: { top: 100 } }).then(data => {
saveAs(data, `file.docx`) // save as docx file
})
但是到这里有个问题,导出的表格是有边框有双实线。
2、双边框解决办法
这时我们再去看innerHTML的字符串中,table的标签中,是没有border、border-collapse、 cellspacing这三个属性的。
所以在html-docx-js-typescript在导出word时,识别表格的样式,需要识别标签自带的属性以及style中的样式才能正确展示。
因此,在拿到innerHTML后,我们需要对拿到的字符串进行处理,给每个table标签添加上border、border-collapse和cellspacing三个属性。
想要单线表格,就需要设置border=“0”,border-collapse=“collapse”,以及cellspacing=“-1”。
import { saveAs } from 'file-saver';
import { asBlob } from 'html-docx-js-typescript'
const innerHtmlStr = document.querySelector('.sun-editor-editable')?.innerHTML;
const str = str.replaceAll('<table',`<table border-collapse="collapse" cellspacing='-1' `);
const htmlStr = `
<!DOCTYPE html>
<html lang="en">
<body style="font-family:方正仿宋_GBK;mso-ascii-font-family:'Times New Roman';">
${str }
</body>
</html>
`;
asBlob(htmlStr,{ orientation: 'landscape', margins: { top: 100 } }).then(data => {
saveAs(data, `file.docx`) // save as docx file
})
这样设置后下载的表格就是单实线的表格啦
3、图片大小设置问题
跟表格同理,在获取到的img标签里,没有width属性,所以,无论在img标签的style属性中设置多大的宽度,下载下来的图片,都是那么大,所以在获取到图片后,在img标签上添加width属性几颗设置下载后的图片大小。
import { saveAs } from 'file-saver';
import { asBlob } from 'html-docx-js-typescript'
let str = '';
str = document.querySelector('.sun-editor-editable')?.innerHTML;
str = str.replaceAll('<table',`<table border-collapse="collapse" cellspacing='-1' `);
str = str.replaceAll('<img',`<img width="800" `);
const htmlStr = `
<!DOCTYPE html>
<html lang="en">
<body style="font-family:方正仿宋_GBK;mso-ascii-font-family:'Times New Roman';">
${str }
</body>
</html>
`;
asBlob(htmlStr,{ orientation: 'landscape', margins: { top: 100 } }).then(data => {
saveAs(data, `file.docx`) // save as docx file
})
图片这个问题处理参考http://seozhijia.net/html/176.html,感谢这位解决了我的疑惑,上面表格问题的处理灵感也来自于这个图片处理。