解决vue-pdf查看pdf⽂件及打印乱码的问题前⾔
vue中简单使⽤vue-pdf预览pdf⽂件,解决打印预览乱码问题
vue-pdf 使⽤
安装
npm install --save vue-pdf
引⼊
import pdf from "vue-pdf
⾃定义封装pdf预览组件
<template>
<el-dialog
:visible.sync="pdfDialog"
:
close-on-click-modal="false"
:show-close="false"
width="900px"
top="52px"
>
<div class="pdf" v-show="fileType == 'pdf'">
<p class="arrow">
<!-- 上⼀页 -->
<span
@click="changePdfPage(0)"
class="currentPage"
:
class="{ grey: currentPage == 1 }"
>上⼀页  </span
>
<span >{{ currentPage }} / {{ pageCount }}</span>
<!-- 下⼀页 -->
<span
@click="changePdfPage(1)"
class="currentPage"
:class="{ grey: currentPage == pageCount }"
>  ;下⼀页</span
>    <button @click="$refs.pdf.print()">下载</button>
<span
@click="close"
><i class="el-icon-close"></i
></span>
</p>
<!-- loadPdfHandler:加载事件 src:需要展⽰的PDF地址;currentPage:当前展⽰的PDF页码;pageCount=$event:PDF⽂件总页码;currentPage=$event:⼀开始加载的页⾯-->  <pdf
ref="pdf"
:src="src"
:page="currentPage"
@num-pages="pageCount = $event"
@page-loaded="currentPage = $event"
@loaded="loadPdfHandler"
></pdf>
</div>
</el-dialog>
</template>
<script>
import pdf from "vue-pdf";
export default {
components: { pdf },
props: ["src"],
data() {
return {
filesProps: {
label: "originName"
},
pdfDialog: false,
currentPage: 0, // pdf⽂件页码
pageCount: 0, // pdf⽂件总页数
fileType: "pdf" // ⽂件类型
};
},
methods: {
// 改变PDF页码,val传过来区分上⼀页下⼀页的值,0上⼀页,1下⼀页
changePdfPage(val) {
if (val === 0 && this.currentPage > 1) {
this.currentPage--;
}
if (val === 1 && this.currentPage < this.pageCount) {
this.currentPage++;
}
},
// pdf加载时
loadPdfHandler() {
this.currentPage = 1; // 加载的时候先加载第⼀页
},
handleOpen() {
this.pdfDialog = true;
},
//关闭弹框
close() {
this.pdfDialog = false;
}
}
};
</script>
<style lang="stylus">
.currentPage {
cursor: pointer;
color: #8c8e92;
}
.currentPage:hover {
color: #2761ff;
}
.arrow{
position: fixed;
top: 0px;
left :0px;
z-index: 2;
width: 100%;
background-color: #191919;
padding: 12px 0;
margin: 0;
text-align :center;
}
>>>.el-dialog__body {
color: #606266;
font-size: 14px;
padding:0;
}
</style>
使⽤
<template>
<el-container>
<el-header>
<el-card>
<div>
<el-button
@click="handlePreviewFile"
>PDF 预览</el-button
>
<el-button
type="text"
@click="handleSafetyExperience"
><i class="el-icon-caret-left">返回</i></el-button
>
</div>
</el-card>
</el-header>
<el-main>
<el-card class="card-style">
<pdf-preview ref="pdfSearch" :src="src"></pdf-preview>
</el-card>
</el-main>
</el-container>
</template>
<script>
import PdfPreview from "../widget/PdfPreview";
export default {
name: "InfoExperience",
components: {
PdfPreview
},
data() {
return {
src:
"storage.xuetangx/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf"  };
},
created() {},
methods: {
handlePreviewFile() {
this.$refs.pdfSearch.handleOpen();
},
handleSafetyExperience() {
this.$router.push({ path: "/safetyApp/sharedExperience" });
}
}
};
</script>
<style scoped></style>
预览效果
点击下载打印预览
预览出现乱码
pdf打印乱码解决办法
打开vue-pdf插件⽬录node_modules/vue-pdf/src/pdfjsWrapper.js
解决办法
乱码解决,打印预览正常
修改后pdfjsWrapper.js源码
以下为本⼈修改的pdfjsWrapper.js⽂件,亲测解决乱码问题
import { PDFLinkService } from 'pdfjs-dist/lib/web/pdf_link_service';
export default function(PDFJS) {
function isPDFDocumentLoadingTask(obj) {
return typeof(obj) === 'object' && obj !== null && obj.__PDFDocumentLoadingTask === true;
}
function createLoadingTask(src, options) {
var source;
if ( typeof(src) === 'string' )
source = { url: src };
else if ( src instanceof Uint8Array )
source = { data: src };
else if ( typeof(src) === 'object' && src !== null )
source = Object.assign({}, src);
else
throw new TypeError('invalid src type');
var loadingTask = Document(source);
loadingTask.__PDFDocumentLoadingTask = true; // since PDFDocumentLoadingTask is not public  if ( options && Password )
if ( options && Progress )
return loadingTask;
}
function PDFJSWrapper(canvasElt, annotationLayerElt, emitEvent) {
var pdfDoc = null;
var pdfPage = null;
var pdfRender = null;
var canceling = false;
function clearCanvas() {
}
function clearAnnotations() {
while ( annotationLayerElt.firstChild )
}
this.destroy = function() {
if ( pdfDoc === null )
return;
pdfDoc.destroy();
pdfDoc = null;
}
return canvasElt.offsetWidth / canvasElt.width;
}
this.printPage = function(dpi, pageNumberOnly) {
if ( pdfPage === null )
return;
// 1in == 72pt
// 1in == 96px
var PRINT_RESOLUTION = dpi === undefined ? 150 : dpi;
var PRINT_UNITS = PRINT_RESOLUTION / 72.0;
var CSS_UNITS = 96.0 / 72.0;
// var iframeElt = ateElement('iframe');
var printContainerElement = ateElement('div');
printContainerElement.setAttribute('id', 'print-container')
// function removeIframe() {
//
/
/ veChild(iframeElt);
function removePrintContainer() {
veChild(printContainerElement);
}
new Promise(function(resolve, reject) {
// iframeElt.frameBorder = '0';
// iframeElt.scrolling = 'no';
// iframeElt.width = '0px;'
// iframeElt.height = '0px;'
// iframeElt.style.cssText = 'position: absolute; top: 0; left: 0';
//
/
/ load = function() {
//
// tWindow);
// }
//
// window.document.body.appendChild(iframeElt);
printContainerElement.frameBorder = '0';
printContainerElement.scrolling = 'no';
printContainerElement.width = '0px;'
printContainerElement.height = '0px;'
printContainerElement.style.cssText = 'position: absolute; top: 0; left: 0';
window.document.body.appendChild(printContainerElement);
resolve(window)
})
.then(function(win) {
win.document.title = '';
Page(1)
.then(function(page) {
var viewport = Viewport(1);
// win.document.head.appendChild(ateElement('style')).textContent =
printContainerElement.appendChild(ateElement('style')).textContent =
'@supports ((size:A4) and (size:1pt 1pt)) {' +
'@page { margin: 1pt; size: ' + ((viewport.width * PRINT_UNITS) / CSS_UNITS) + 'pt ' + ((viewport.height * PRINT_UNITS) / CSS_UNITS) + 'pt; }' +  '}' +
'#print-canvas { display: none }' +
'@media print {' +
'body { margin: 0 }' +
'canvas { page-break-before: avoid; page-break-after: always; page-break-inside: avoid }' +
'#print-canvas { page-break-before: avoid; page-break-after: always; page-break-inside: avoid; display: block }' +
'body > *:not(#print-container) { display: none; }' +
'}'+
'@media screen {' +
'body { margin: 0 }' +
// '}'+
//
// ''
'}'
return win;
})
})
.then(function(win) {
var allPages = [];
for ( var pageNumber = 1; pageNumber <= pdfDoc.numPages; ++pageNumber ) {
if ( pageNumberOnly !== undefined && pageNumberOnly.indexOf(pageNumber) === -1 )
continue;
allPages.push(
.then(function(page) {
var viewport = Viewport(1);
// var printCanvasElt = win.document.body.appendChild(ateElement('canvas'));
var printCanvasElt = printContainerElement.appendChild(ateElement('canvas'));
printCanvasElt.setAttribute('id', 'print-canvas')
printCanvasElt.width = (viewport.width * PRINT_UNITS);
printCanvasElt.height = (viewport.height * PRINT_UNITS);
der({
canvasContext: Context('2d'),
transform: [ // Additional transform, applied just before viewport transform.
PRINT_UNITS, 0, 0,
PRINT_UNITS, 0, 0
],
viewport: viewport,
intent: 'print'
}).promise;
})
);
}
Promise.all(allPages)
.then(function() {
win.focus(); // Required for IE
if (win.document.queryCommandSupported('print')) {
Command('print', false, null);
} else {
win.print();
}
// removeIframe();
removePrintContainer();
})
.
catch(function(err) {
// removeIframe();
removePrintContainer();
emitEvent('error', err);
})
})
}
if ( pdfRender !== null ) {
if ( canceling )
return;
canceling = true;
pdfRender.cancel();
return;
}
if ( pdfPage === null )
return;
if ( rotate === undefined )
rotate = ate;
var scale = canvasElt.offsetWidth / Viewport(1).width * (window.devicePixelRatio || 1);
var viewport = Viewport(scale, rotate);
emitEvent('page-size', viewport.width, viewport.height);
canvasElt.width = viewport.width;
canvasElt.height = viewport.height;
js assignpdfRender = der({
canvasContext: Context('2d'),
viewport: viewport
});
annotationLayerElt.style.visibility = 'hidden';
clearAnnotations();
var viewer = {
scrollPageIntoView: function(params) {
emitEvent('link-clicked', params.pageNumber)
},
};
var linkService = new PDFLinkService();
linkService.setDocument(pdfDoc);