|
|
<template> <div class="preview-wrapper"> <div class="collect-header" style="justify-content: flex-start; border-top: none; "> <h4 class="is-file" style="flex:none; width: 120px;">原文</h4> <span style="font-size: 12px; flex: 1; line-height: 42px;">所属文件:{{ parentArchiveNo }}</span> </div> <!-- <div class="top-container"> <div class="top-left"> <input class="file-select" type="file" @change="handleChange" > </div> <div class="top-middle"> 文件预览 </div> <div class="top-right"> <el-button @click="printWindow"> <i class="el-icon-printer" />window </el-button> <el-button v-print="printObj">vue-print打印</el-button> <el-button type="primary" @click="toImg">转图片打印</el-button> </div> </div> --> <div class="main-content"> <div class="content-list"> <h4 class="arc-title">原文列表</h4> <ul v-if="allFileTables.length!==0" class="file-list"> <li v-for="(item,index) in allFileTables" :key="index" :class="{'active-file': item.id == fileCurrent.id}" @click="selectFile(item)"> <span>{{ item.file_name }}</span> <i class="iconfont icon-attachment" /> </li> </ul> <el-empty v-else :image-size="100" /> </div> <div v-loading="loading" element-loading-text="文件加载中" class="content-right"> <div class="preview-info"> <ul> <li>创建时间:{{ fileCurrent && fileCurrent.create_time }}</li> <li>大小:{{ getFileSize(fileCurrent && fileCurrent.file_size) }}</li> <li>尺寸:{{ (!(fileCurrent && fileCurrent.file_dpi) || (fileCurrent && fileCurrent.file_dpi === 'null')) ? '-' : fileCurrent.file_dpi }}</li> </ul> <div class="preview-btn"> <el-button :loading="downloading" class="iconfont icon-xiazai" @click="downloadFile(fileCurrent)">下载</el-button> <el-button v-print="printObj" class="iconfont icon-dayin">打印</el-button> </div> </div> <div id="printArea" ref="output" class="well-box" :style="{overflowY : !loading ? 'auto' : 'hidden'}" /> <div class="water-mask" /> </div> </div> </div></template>
<script>import { FetchMinioReDocumentBase64ByFileId } from '@/api/prearchiveLibrary/prearchiveLibrary'// import { FetchBase64ByFileId } from '@/api/archivesManage/library'
import { getExtend, readBuffer, render } from '@/components/util'import { parse } from 'qs'import { watermark } from '@/utils/waterMark'import { getInitWatermark } from '@/api/system/waterMask'import { downloadFile } from '@/utils/index'import { mapGetters } from 'vuex'import html2canvas from 'html2canvas' // 转图片打印需要先安装html2Canvas和print-js
import printJS from 'print-js'import { getToken } from '@/utils/auth'
export default { name: 'Preview', components: { }, props: { msg: { type: String, default: '' } }, data() { return { downloading: false, src: '', logo: require('../../assets/images/logo.png'), // 加载状态跟踪
loading: false, // 上个渲染实例
last: null, // 隐藏头部,当基于消息机制渲染,将隐藏
hidden: false, printObj: { id: 'printArea', preview: true, // 是否启动预览模式,默认是false
previewTitle: '电子原文预览', // 打印预览的标题
previewPrintBtnLabel: '预览结束,开始打印', zIndex: 20002, // 预览窗口的z-index,默认是20002,最好比默认值更高
extraCss: '', // 打印可引入外部的一个css文件
extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>,<style> #printArea { height: auto !important; } <style>', // 打印头部文字
previewBeforeOpenCallback() { console.log('正在加载预览窗口!') }, // 预览窗口打开之前的callback
previewOpenCallback() { console.log('已经加载完预览窗口,预览打开了!') }, // 预览窗口打开时的callback
beforeOpenCallback() { console.log('开始打印之前!') }, // 开始打印之前的callback
openCallback() { console.log('执行打印了!') }, // 调用打印时的callback
closeCallback() { console.log('关闭了打印工具!') }, // 关闭打印的callback(无法区分确认or取消)
clickMounted() { console.log('点击v-print绑定的按钮了!') }, // url: 'http://192.168.99.67:11100/downloadFile/category/AE8B188F0C0314F9BE31B8/82FBCAE96CBC9F50809838/7f3df862-f36d-4061-9c3e-e81556420742.pdf', // 打印指定的URL,确保同源策略相同
// asyncUrl (reslove) {
// setTimeout(() => {
// reslove('http://localhost:8080/')
// }, 2000)
// },
standard: '', extarCss: '' }, watermarkInfo: null, timer: null, parentArchiveNo: null, allFileTables: [], toFile: null, fileCurrent: null, fileParentInfo: null, pdfsArray: [], documentId: null } }, computed: { ...mapGetters([ 'baseApi' ]) }, created() { // 允许使用预留的消息机制发送二进制数据,必须在url后添加?name=xxx.xxx&from=xxx
const { from, name } = parse(location.search.substr(1)) if (from) { window.addEventListener('message', (event) => { const { origin, data: blob } = event if (origin === from && blob instanceof Blob) { // 构造响应,自动渲染
const file = new File([blob], name, {}) this.hidden = true this.handleChange({ target: { files: [file] }}) } }) } }, mounted() { if (this.$route.query.archiveNo) { this.parentArchiveNo = this.$route.query.archiveNo } if (localStorage.getItem('documentId')) { this.documentId = JSON.parse(localStorage.getItem('documentId')) } if (localStorage.getItem('fileParentInfo')) { this.fileParentInfo = JSON.parse(localStorage.getItem('fileTables')) }
if (localStorage.getItem('fileTables')) { this.allFileTables = JSON.parse(localStorage.getItem('fileTables')) } if (localStorage.getItem('fileCurrent')) { this.fileCurrent = JSON.parse(localStorage.getItem('fileCurrent')) } this.getBase64ByFileId() }, methods: { getFileSize(fileSize) { const fileSizeInKB = (fileSize / 1024).toFixed(2) + 'kB' const fileSizeInB = fileSize + 'B' return (fileSize / 1024) <= 0.01 ? fileSizeInB : fileSizeInKB }, // 下载附件
downloadFile(row) { // filePath 保存的文件路径
// bucketType 1预归档 2档案
this.downloading = true let bucketType = null if (this.documentId) { bucketType = 1 } else { bucketType = 2 } const url = this.baseApi + '/api/minioUpload/getFile?filePath=' + row.file_path + '&bucketType=' + bucketType const fetchOptions = { method: 'GET', headers: { 'Authorization': getToken() } } fetch(url, fetchOptions).then(res => res.blob()).then(blob => { downloadFile(blob, row.file_name.split('.')[0], row.file_type) this.downloading = false }).catch(() => { this.$message({ message: '下载文件失败', type: 'error', offset: 8 }) this.downloading = false }) }, selectFile(item) { this.fileCurrent = item this.getBase64ByFileId() }, getBase64ByFileId() { this.loading = true if (this.documentId) { const params = { 'filePath': this.fileCurrent.file_path, 'bucketType': 1 } FetchMinioReDocumentBase64ByFileId(params).then(res => { var base64String = res var fileName = this.fileCurrent && this.fileCurrent.file_name var mimeType = this.fileCurrent && this.fileCurrent.file_type this.toFile = this.base64ToFile(base64String, fileName, mimeType) if (this.toFile) { this.handleChange() } }) } else { const params = { 'filePath': this.fileCurrent.file_path, 'bucketType': 2 } FetchMinioReDocumentBase64ByFileId(params).then(res => { console.log('res', res) var base64String = res var fileName = this.fileCurrent && this.fileCurrent.file_name var mimeType = this.fileCurrent && this.fileCurrent.file_type this.toFile = this.base64ToFile(base64String, fileName, mimeType) if (this.toFile) { this.handleChange() } }) } }, base64ToFile(base64String, fileName, mimeType) { var byteCharacters = atob(base64String) var byteArrays = [] for (var offset = 0; offset < byteCharacters.length; offset += 512) { var slice = byteCharacters.slice(offset, offset + 512) var byteNumbers = new Array(slice.length) for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i) } var byteArray = new Uint8Array(byteNumbers) byteArrays.push(byteArray) } var file = new Blob(byteArrays, { type: mimeType }) file.name = fileName return file }, toImg() { // 转图片打印
html2canvas(this.$refs.output, { backgroundColor: null, useCORS: true, windowHeight: document.body.scrollHeight }).then((canvas) => { // let url = canvas.toDataURL('image/jpeg', 1.0)
const url = canvas.toDataURL() this.img = url printJS({ printable: url, type: 'image', documentTitle: '打印图片' }) }) }, getWatermark() { getInitWatermark().then((res) => { this.watermarkInfo = res // this.isEnable = this.watermarkInfo.isEnable
if (res.watermarkType === '1') { watermark({ watermark_txt: this.watermarkInfo.context, watermark_alpha: parseFloat(this.watermarkInfo.transparency) / 100 }, 'water-mask', 'img') } else if (res.watermarkType === '0') { // if (parent.length > 0) {
// for (let i = 0; i < parent.length; i++) {
// const childImg = parent[i].getElementsByClassName('weterbox')
// if (childImg.length > 0) {
// for (let i = 0; i < childImg.length; i++) {
// parent[i].removeChild(childImg[i])
// }
// }
// }
// }
watermark({ watermark_txt: this.watermarkInfo.context, watermark_color: this.watermarkInfo.transparency, watermark_fontsize: this.watermarkInfo.watermarkFont + 'px' }, 'water-mask', 'text') } if (document.getElementById('error-tip')) { document.getElementsByClassName('water-mask')[0].innerHTML = '' } }).catch(err => { console.log(err) }) }, async handleChange(e) { try { clearTimeout(this.timer) // const [file] = e.target.files
// console.log('file', file)
const fileReader = new FileReader() fileReader.readAsArrayBuffer(this.toFile) fileReader.onload = () => { this.src = fileReader.result } const arrayBuffer = await readBuffer(this.toFile) this.last = await this.displayResult(arrayBuffer, this.toFile)
this.$nextTick(() => { // 取得扩展名
const extend = getExtend(this.toFile.name) // 加水印
const maskDiv = document.getElementsByClassName('mask_div') const imgMaskDiv = document.getElementsByClassName('weterbox')
if (imgMaskDiv.length === 1) { document.getElementsByClassName('water-mask')[0].removeChild(imgMaskDiv[0]) } // docx-wrapper docx
for (var j = maskDiv.length - 1; j >= 0; j--) { document.getElementsByClassName('water-mask')[0].removeChild(maskDiv[j]) }
if (!extend.includes('pdf')) { this.getWatermark() } }) } catch (e) { console.error(e) } finally { this.timer = setTimeout(() => { this.loading = false }, 1000) } }, displayResult(buffer, file) { // 取得文件名
const { name } = file // 取得扩展名
const extend = getExtend(name) // 输出目的地
const { output } = this.$refs // 生成新的dom
const node = document.createElement('div') // 添加孩子,防止vue实例替换dom元素
if (this.last) { output.removeChild(this.last.$el) this.last.$destroy() } const child = output.appendChild(node) // 调用渲染方法进行渲染
return new Promise((resolve, reject) => render(buffer, extend, child).then(resolve).catch(reject) ) }, // 打印ofd文件
async printWindow() { /* if (this.showScale !== 0) { this.showScale = 0; const divs = renderOfd(this.domWidth, this.ofdObj); await this.displayOfdDiv(divs); }*/ const childs = this.$refs.output.children const list = [] for (const page of childs) { list.push(page.cloneNode(true)) } if (list.length > 0) { const printWindow = window.open('打印窗口', '_blank') // 给新打开的标签页添加画布内容
const documentBody = printWindow.document.body
// 需要给新打开的标签页添加样式,否则打印出来的内容会很错位
documentBody.style.marginTop = '20px' for (const page of list) { // 为了让打印的内容不会太靠上,所以给每一页都添加一个marginBottom
page.style.marginBottom = '20px' documentBody.appendChild(page) } // 焦点移到新打开的标签页
printWindow.focus() // 执行打印的方法(注意打印方法是打印的当前窗口内的元素,所以前面才新建一个窗口:print()--打印当前窗口的内容。)
printWindow.print() // 操作完成之后关闭当前标签页(点击确定或者取消都会关闭)
printWindow.close() } } }}</script><style media="print" lang="scss">@page { size: auto; margin: 3mm;}@media print { html { background-color: #ffffff; height: auto; margin: 0px; }
body { border: solid 1px #ffffff; margin: 10mm 15mm 10mm 15mm; } table { table-layout: auto !important; }
.el-table__header-wrapper .el-table__header { width: 100% !important; border: solid 1px #f2f2f2; } .el-table__body-wrapper .el-table__body { width: 100% !important; } #pagetable table { table-layout: fixed !important; }}</style><style lang="scss" scoped>.preview-wrapper{ background-color: #f6f8fc; .collect-header{ background-color: #fff; border-bottom: 1px solid #edeff3; }}.top-container{ display: flex; justify-content: space-between; padding: 0 20px; height: 50px; line-height: 50px; overflow: hidden; text-align: center; align-items: center; color: #000; .top-middle{ flex:1; text-align: center; font-size: 20px; font-weight: bold; } .top-right{ text-align: center; align-items: center; display:flex; justify-content: flex-end; .el-button{ padding: 0 4px; height: 30px; line-height: 30px; } }}
.main-content{ display: flex; justify-content: space-between; width: calc(100%); height: calc(100vh - 75px); background-color: #fff;
.content-list{ width: 300px; .arc-title{ height: 48px; line-height: 48px; text-align: center; font-size: 16px; color: #0c0e1e; background-color: #f3f5f8; } .file-list{ height: calc(100% - 48px); padding: 10px 0; font-size: 12px; overflow: hidden; overflow-y: scroll; li{ display: flex; justify-content: space-between; padding: 0 10px 0 20px; line-height: 26px; margin-bottom: 4px; cursor:default; &.active-file{ background-color: #e8f2ff; color: #0c0e1e; } & span{ display: block; margin-right: 4px; } &:hover{ background-color: #e8f2ff; color: #0c0e1e; } } } } .content-right{ position: relative; width: calc(100% - 300px); border: 1px solid #edeff3; border-top: none; border-bottom: none; // overflow-y: auto;
}}.well-box{ position: relative; border: 1px solid #edeff3; background-color: #f6f8fc; height: calc(100vh - 150px); margin: 0 10px; overflow: hidden;}.water-mask{ position: fixed; left: 300px; top: 150px; bottom: 10px; right: 10px; width:100%; z-index:99; pointer-events: none;}.preview-info{ display: flex; justify-content: space-between; padding: 15px; ul{ display: flex; justify-content: flex-start; font-size: 14px; li{ margin-right: 10px; height: 30px; line-height: 30px } } .preview-btn{ .el-button.icon-dayin{ &::before{ font-size: 16px; } } }}</style>
<style>.pptx-wrapper { max-width: 1000px; margin: 0 auto;}.el-loading-mask{ position: fixed; left: 300px; top: 75px;}</style>
|