<el-button type="primary"
size="mini"
@click="getPDFLoadFile">预 览</el-button>
<el-button type="primary"
size="mini"
@click="getDownloadPdf">导 出</el-button>
<el-button type="primary"
size="mini"
@click="getPrintPdf">打 印</el-button>
<div class="pdf-container f-col" ref="report_pdf">
<canvas v-for="pageIndex in pdfPages"
:id="`pdf-canvas-`+pageIndex"
:key="pageIndex"></canvas>
</div>
npm i print-js
<script>
import * as PdfJs from 'pdfjs-dist/legacy/build/pdf.js'
export default {
data () {
return {
pdfUrl: '',
pdfDoc: '',
pdfPages: 0,
pdfScale: 1.0
}
}
}
methods:{
async getPDFLoadFile () {
let params = this.reportForm
let item = this.currentReport
let url = await api.getReportPDF(item.id, params);
this.pdfUrl = url
PdfJs.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry')
let urlPdf = window.URL.createObjectURL(new Blob([url]))
const loadingTask = PdfJs.getDocument(urlPdf)
loadingTask.promise.then(pdf => {
this.pdfDoc = pdf
this.pdfPages = this.pdfDoc.numPages
this.$nextTick(() => {
this.renderPage(1)
})
})
},
renderPage (num) {
this.pdfDoc.getPage(num).then(page => {
const canvasId = 'pdf-canvas-' + num
const canvas = document.getElementById(canvasId)
const ctx = canvas.getContext('2d')
const dpr = window.devicePixelRatio || 1
const viewport = page.getViewport({ scale: this.pdfScale })
canvas.width = viewport.width * dpr
canvas.height = viewport.height * dpr
canvas.style.width = viewport.width + 'px'
canvas.style.height = viewport.height + 'px'
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
const renderContext = {
canvasContext: ctx,
viewport: viewport
}
page.render(renderContext)
if (num < this.pdfPages) {
this.renderPage(num + 1)
}
})
},
getDownloadPdf () {
let item = this.currentReport
const blob = new Blob([this.pdfUrl], { type: 'application/pdf' })
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob)
downloadElement.href = href
downloadElement.download = item.name + '.pdf'
document.body.appendChild(downloadElement)
downloadElement.click()
document.body.removeChild(downloadElement)
window.URL.revokeObjectURL(href)
},
getPrintPdf () {
const blob = new Blob([this.pdfUrl], { type: 'application/pdf' })
const url = window.URL.createObjectURL(blob)
const iframe = document.createElement('iframe')
iframe.style.display = 'none'
iframe.src = url
document.body.appendChild(iframe)
iframe.onload = function () {
console.log(iframe.contentWindow);
iframe.contentWindow.print()
window.URL.revokeObjectURL(url)
}
},
}
</script>