javascript || jquery

[javascript] export2doc doc파일 다운로드

솨솨_ 2024. 7. 31. 13:52

 

html을 doc파일로 다운로드 받고 싶을때 사용하는 방법이다

var html = [];

function export2doc(fileName) {
	html.splice(0);
    
	// header
    var static = {
        mhtml: {
            top: "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\">\n_html_</html>",
            head: "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<xml><w:WordDocument><w:View>Print</w:View><w:Compatibility><w:UseFELayout/></w:Compatibility></w:WordDocument></xml><meta name=\"ProgId\" content=Word.Document><meta name=\"Generator\" content=\"Microsoft Word 9\"><meta name=\"Originator\" content=\"Microsoft Word 9\">\n<style>\n_styles_\n</style>\n</head>\n",
            body: "<body>_body_</body>"
        }
    };

	//html
     var htmlInner = '<div>내용</div>';
     html.push(htmlInner);
    
     var  styles = (
            `@page { mso-page-border-surround-header: no; mso-page-border-surround-footer: no; }
             @page word-sections { size: A4; margin: 10mm 10mm 10mm 10mm; mso-header-margin: 0pt; mso-footer-margin: 0pt;mso-title-page: no;mso-paper-source: 0; layout-grid: 0; page-break-before: always; page-break-inside: avoid;  }
             div.word-sections { page: word-sections; }
            `
        );


	var fileContent = static.mhtml.top.replace("_html_", static.mhtml.head.replace("_styles_", styles) + static.mhtml.body.replace("_body_", html));
    //html 안에 table, div을 추가해서 넣을 시 replaceAll을 사용해 콤마를 제거 해 준다.
    //ex) var fileContent = fileContent.replaceAll(',<table','<table');

	var blob = new Blob([fileContent], { type: "application/msword;charset=utf-8" });

	saveAs(blob, fileName + ".doc");
  
}

 export2doc(doc다운로드);