我有一个将我的HTML Div部分转换为Word文档的功能。我已经使用了嵌入CSS文件中的各种样式。尽管这些样式在显示时隐含于HTML div,但这些样式并未传递到随后创建的文档中。创建Word文档时,如何同时传递CSS和HTML div?请从html div中找到用于创建文档的功能
function Export2Doc(element, filename = ''){
var preHtml = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
var postHtml = "</body></html>";
var html = preHtml+document.getElementById(element).innerHTML+postHtml;
var blob = new Blob(['\ufeff', html], {
type: 'application/msword'
});
// Specify link url
var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);
// Specify file name
filename = filename?filename+'.doc':'document.doc';
// Create download link element
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob ){
navigator.msSaveOrOpenBlob(blob, filename);
}else{
// Create a link to the file
downloadLink.href = url;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
document.body.removeChild(downloadLink);
}
答案 0 :(得分:0)
如果转换后的文档支持css样式,则可以像这样转换之前将css代码注入html中:
const el = document.querySelector('#yourElement').cloneNode(true)
const style = document.createElement('style')
style.innerHTML = `
div {
height: 100%;
}
` // your styles
const wrapper = document.querySelector('div') // put them inside a wrapper
wrapper.appendChild(style)
wrapper.appendChild(el)
// Then convert `wrapper`