前端使用 docx-preview 和 window.print() 预览打印 word 文档
前端使用 docx-preview 和 window.print() 预览打印 word 文档
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <el-dialog title="文稿" :visible.sync="visible"> xxxxxxxxxxxxxxxxxxxxxxxxx <div slot="footer" class="dialog-footer"> <el-button @click="visible = false">取 消</el-button> <el-button type="primary" @click="confirm('download')">下载</el-button> <el-button @click="confirm('preview')">预览</el-button> </div> <el-dialog fullscreen="" width="30%" title="预览" :visible.sync="innerVisible" append-to-body=""> <div ref="file" class="preview print-content"></div> <div slot="footer" class="dialog-footer"> <el-button type="primary" @click="confirm('print')">打印</el-button> </div> </el-dialog> </el-dialog>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| import { api } from '@/api'; import { renderAsync } from 'docx-preview'; function downloadBlob(blob, fileName) { if (!fileName) { alert('文件名不正确'); return; } var reader = new FileReader(); reader.readAsDataURL(blob); reader.onload = function (e) { var a = document.createElement('a'); a.download = fileName; a.href = e.target.result; document.body.appendChild(a); a.click(); document.body.removeChild(a); }; } export default { data() { return { innerVisible: false, visible: false, radio: null, form: {} }; }, methods: { show(form) { this.visible = true; }, hide() { this.visible = false; }, confirm(type) { api.getPrintFile() .then(res => { console.log('这是一个Blob对象',res); if (res && res.size) { const fileName = Math.random(); if (type == 'download') { downloadBlob(res, fileName + '.docx'); this.hide(); } else if (type == 'preview') { this.innerVisible = true; this.$nextTick(() => { renderAsync( res, this.$refs.file, null, { className: 'docx', inWrapper: true, ignoreWidth: true, ignoreHeight: true, ignoreFonts: true, breakPages: true, ignoreLastRenderedPageBreak: true, experimental: true, trimXmlDeclaration: true, debug: false, }, ); }); } else if (type == 'print') { const printHtml = document.querySelector('.print-content').innerHTML; const newWin = window.open('', 'newwindow'); newWin.document.write(`<title>${this.contractTemplate}</title>`); newWin.document.write(``); newWin.document.write(printHtml); newWin.document.write(''); newWin.print(); newWin.close(); } else { this.$message.warning('type error'); } } else { this.$message.warning('下载出错,请查看接口返回值'); console.warn(res); } });
}, }, };
|