在做項目時,要將富文本編輯器,或是html內容 導出爲word。
先引入文件保存js
<script src="FileSaver.js"></script>
導出爲Docx
docx體積更小,而且word2007也可以打開
1.引用插件html-docx.js
<script src="html-docx.js"></script>
2.構建完整的html內容文檔
var content = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>'+ 要導出的html信息 +'</html>'
content要導出的html信息,建議在服務端自己拼接完成。
若是想從頁面抓取html信息,可以用下面的方法(不建議,客戶端消耗高)
html:
<div id="content">
要導出的html信息
<img src="xxx">
</div>
function convertImagesToBase64 (content) {
var regularImages = content.querySelectorAll("img");
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
[].forEach.call(regularImages, function (imgElement) {
// preparing canvas for drawing
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = imgElement.width;
canvas.height = imgElement.height;
ctx.drawImage(imgElement, 0, 0);
// by default toDataURL() produces png image, but you can also export to jpeg
// checkout function's documentation for more details
var dataURL = canvas.toDataURL();
imgElement.setAttribute('src', dataURL);
})
canvas.remove();
}
var content = document.getElementById('#content');
convertImagesToBase64(content);//轉換圖片爲base64
content = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>'+ content +'</html>'
3.利用腳本導出word
var converted = htmlDocx.asBlob(content);
saveAs(converted, 'test.docx');// 用 FielSaver.js裏的保存方法 進行輸出
導出爲Doc
利用wordjquery 這個
1.引入jquery和wordexport
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="wordexport.js"></script>
2.使用導出
$(元素).wordExport(文件名,isBase64)
isBase64 用於標識 元素中的圖片是否都處理爲了base64,默認爲false,內置處理方法,可以去看看
注意
無論是html-docx.js還是 wordexport.js 都需要將html中的圖片轉爲base64形式
而且,圖片的寬度高,最好自己設置下,否則下載的圖片會以圖片原始大小下載,就會出現以下,圖片在文檔超出情況
處理圖片的寬高,可以採用 正則替換,這裏給出兩種替換參考(平時不太寫正則,所以有點挫)
C#:
string reg = "<img.*? src=[\"'](.*?)['\"].*?>";
MatchCollection collections = Regex.Matches(description, reg);
if (collections.Count > 0)
{
foreach (Match match in collections)
{
Regex regWidth = new Regex("width\\s*=\\s*\\S+ ");
if (!regWidth.IsMatch(img))//img 中不存在width
{
//獲取其他屬性進行替換
Regex reg1 = new Regex(@"style\s*=(['""\s]?)[^'""]*?\1"); ;
img = reg1.Replace(img, "width=\"350\" height=\"216\" ");//按黃金比例替換
}
else
{
Match mathWidth = regWidth.Match(img);
if (mathWidth.Success)
{
string widh = mathWidth.Value.Substring(7).Substring(0, mathWidth.Value.Substring(7).Length - 2);//width
if (int.Parse(widh) > 400) {//原寬超出400
Regex regHeight = new Regex(@"height\s*=(['""\s]?)[^'""]*?\1");
Match mathHeight = regHeight.Match(img);
if (mathHeight.Success)
{
string height = mathHeight.Value.Substring(8).Substring(0, mathHeight.Value.Substring(8).Length - 1);
img = regHeight.Replace(img, "height=\" " + 350 * int.Parse(height) / int.Parse(widh) + "\"");//按比例替換 高
}
img = regWidth.Replace(img, "width=\"350\"");
}
}
}
}
}
若是二進制流存儲的圖片數據,可以通過Bitmp來讀取原始大小 ,然後按照原始比例再進行縮放
//通過二進制流 獲取圖片原始寬高
private int[] GetScaleImgSizeByByte(byte[] image)
{
MemoryStream stream = new MemoryStream(image);//內存流寫入
Bitmap bmp = new Bitmap(stream);
int width = 600;//先指定一個固定大小 和word頁面邊距最大寬差不多
int height = 600;
if (bmp.Width > 600)
{
height = (int)(width * ((double)bmp.Height / (double)bmp.Width));
}
if (height > 600 || bmp.Height > 600)
{//調完寬後判斷高
height = 600;
width = (int)(height / ((double)bmp.Height / (double)bmp.Width));
}
return new int[] { width, height };
}
js正則替換:
var str = htmlText.replace(/(<img[^>]*)(\/?>)/gi, function (match, capture) {
if(match.match(/width\s*?=\s*?([‘"])[\s\S]*?\1/ig)==null)
match = match.replace(/(<img[^>]*)(\/?>)/gi,"$1 width='350' $2")//沒有寬就增加寬
return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, '').replace(/width\s*?=\s*?([‘"])[\s\S]*?\1/ig ,"width='350'");
});