问题描述
这是从javascript函数创建word文件的代码的一部分
我想在文件中添加一个图像(图像必须是服务器硬盘上的物理图像,而不是互联网上的 URL)
如何实现这一点
var templateHeader = '<html xmlns:v="urn:schemas-microsoft-com:vml"\
xmlns:o="urn:schemas-microsoft-com:office:office"\
xmlns:w="urn:schemas-microsoft-com:office:word"\
xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"\
xmlns:css="http://macVmlSchemaUri" xmlns="http://www.w3.org/TR/REC-html40">\
<head>\
<Meta name=Title content="">\
<Meta name=Keywords content="">\
<Meta http-equiv=Content-Type content="text/html; charset=unicode">\
<Meta name=ProgId content=Word.Document>\
<Meta name=Generator content="Microsoft Word 14">\
<Meta name=Originator content="Microsoft Word 14">\
<link rel=File-List href="Customer%20(5)_files/filelist.xml">\
<!--[if gte mso 9]><xml>\
<w:WordDocument>\
<w:View>Print</w:View>\
</w:WordDocument>\
</xml><![endif]-->\
<style>';
templateHeader += '<!--@page WORDSECTION1 {mso-page-orientation:potrait;} -->';
templateHeader += '</style></head><body bgcolor=white lang=EN-US style=\'tab-interval:36.0pt\'><div class=WordSection1>';
var templateFooter = '<p class=Msonormal style=\'mso-margin-top-alt:auto;mso-margin-bottom-alt:auto\'><span style=\'mso-fareast-font-family:"Times New Roman";mso-bidi-font-family:"Times New Roman"\'><o:p> </o:p></span></p></div></body></html>';
var charset = document.characterSet || document.charset;
saveAs(new Blob(["\ufeff",templateHeader + "This is my file" + templateFooter],{
type: 'application/msword;charset='+ charset,encoding: charset
}),"filename" + '.doc');
解决方法
由于其余部分也是 HTML,因此也可以将图像添加为 HTML:
var image = '<img src="https://www.gravatar.com/avatar/fda292124649edada394b86c22a9103d?s=64&d=identicon&r=PG" width="32" height="32">';
function getDataUri(url,callback) {
var image = new Image();
image.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
canvas.getContext('2d').drawImage(this,0);
// Get raw image data
callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/,''));
// ... or get as Data URI
callback(canvas.toDataURL('image/png'));
};
image.src = url;
}
// Usage
getDataUri(image,function(dataUri) {
saveAs(new Blob(["\ufeff",templateHeader + "This is my file" + dataUri + templateFooter],{
type: 'application/msword;charset='+ charset,encoding: charset
}),"filename" + '.doc');
});