• PDF文件在线预览


    安装vue-pdf

    npm install vue-pdf
    

    vue页面中引入

    1. import pdf from 'vue-pdf';
    2. components: {pdf},

    在vue页面中使用

    1. <el-button
    2. size="mini"
    3. type="text"
    4. icon="el-icon-edit"
    5. @click="handlePreview(scope.row)"
    6. >预览</el-button>
    7. pdfUrl:'',
    8. src:'',
    9. pdfPreviewDialog:false,
    10. numPages:100,
    11. currentPage:1,
    12. handlePreview(row){
    13. this.pdfUrl=this.baseUrl+row.pdfPath;
    14. this.src=pdf.createLoadingTask(this.pdfUrl);
    15. this.pdfPreviewDialog=true;
    16. this.src.promise.then(pdf => {
    17. this.numPages = pdf.numPages;
    18. });
    19. },
    20. <el-dialog :visible.sync="pdfPreviewDialog" title="简历" width="50%" center>
    21. <div>
    22. <button @click="$refs.pdf.print()">打印</button>
    23. <pdf :src="src" style="width:100%" ref="pdf" :page="currentPage" @page-loaded="currentPage = $event">
    24. </pdf>
    25. </div>
    26. <el-pagination background layout="prev, pager, next" :page-size="1" :total="numPages" @current-change="changePage">
    27. </el-pagination>
    28. </el-dialog>

    安装的vue-pdf里某个js文件pdfjsWrapper.js的修改如下,防止打印乱码:

    1. import { PDFLinkService } from 'pdfjs-dist/es5/web/pdf_viewer';
    2. var pendingOperation = Promise.resolve();
    3. export default function(PDFJS) {
    4. function isPDFDocumentLoadingTask(obj) {
    5. return typeof(obj) === 'object' && obj !== null && obj.__PDFDocumentLoadingTask === true;
    6. // or: return obj.constructor.name === 'PDFDocumentLoadingTask';
    7. }
    8. function createLoadingTask(src, options) {
    9. var source;
    10. if ( typeof(src) === 'string' )
    11. source = { url: src };
    12. else if ( src instanceof Uint8Array )
    13. source = { data: src };
    14. else if ( typeof(src) === 'object' && src !== null )
    15. source = Object.assign({}, src);
    16. else
    17. throw new TypeError('invalid src type');
    18. // source.verbosity = PDFJS.VerbosityLevel.INFOS;
    19. // source.pdfBug = true;
    20. // source.stopAtErrors = true;
    21. if ( options && options.withCredentials )
    22. source.withCredentials = options.withCredentials;
    23. var loadingTask = PDFJS.getDocument(source);
    24. loadingTask.__PDFDocumentLoadingTask = true; // since PDFDocumentLoadingTask is not public
    25. if ( options && options.onPassword )
    26. loadingTask.onPassword = options.onPassword;
    27. if ( options && options.onProgress )
    28. loadingTask.onProgress = options.onProgress;
    29. return loadingTask;
    30. }
    31. function PDFJSWrapper(canvasElt, annotationLayerElt, emitEvent) {
    32. var pdfDoc = null;
    33. var pdfPage = null;
    34. var pdfRender = null;
    35. var canceling = false;
    36. canvasElt.getContext('2d').save();
    37. function clearCanvas() {
    38. canvasElt.getContext('2d').clearRect(0, 0, canvasElt.width, canvasElt.height);
    39. }
    40. function clearAnnotations() {
    41. while ( annotationLayerElt.firstChild )
    42. annotationLayerElt.removeChild(annotationLayerElt.firstChild);
    43. }
    44. this.destroy = function() {
    45. if ( pdfDoc === null )
    46. return;
    47. // Aborts all network requests and destroys worker.
    48. pendingOperation = pdfDoc.destroy();
    49. pdfDoc = null;
    50. }
    51. this.getResolutionScale = function() {
    52. return canvasElt.offsetWidth / canvasElt.width;
    53. }
    54. this.printPage = function(dpi, pageNumberOnly) {
    55. if ( pdfPage === null )
    56. return;
    57. // 1in == 72pt
    58. // 1in == 96px
    59. var PRINT_RESOLUTION = dpi === undefined ? 150 : dpi;
    60. var PRINT_UNITS = PRINT_RESOLUTION / 72.0;
    61. var CSS_UNITS = 96.0 / 72.0;
    62. var printContainerElement = document.createElement('div');
    63. printContainerElement.setAttribute('id', 'print-container')
    64. function removePrintContainer() {
    65. printContainerElement.parentNode.removeChild(printContainerElement);
    66. }
    67. new Promise(function(resolve, reject) {
    68. printContainerElement.frameBorder = '0';
    69. printContainerElement.scrolling = 'no';
    70. printContainerElement.width = '0px;'
    71. printContainerElement.height = '0px;'
    72. printContainerElement.style.cssText = 'position: absolute; top: 0; left: 0';
    73. window.document.body.appendChild(printContainerElement);
    74. resolve(window)
    75. })
    76. .then(function(win) {
    77. win.document.title = '';
    78. return pdfDoc.getPage(1)
    79. .then(function(page) {
    80. var viewport = page.getViewport({ scale: 1 });
    81. printContainerElement.appendChild(win.document.createElement('style')).textContent =
    82. '@supports ((size:A4) and (size:1pt 1pt)) {' +
    83. '@page { margin: 1pt; size: ' + ((viewport.width * PRINT_UNITS) / CSS_UNITS) + 'pt ' + ((viewport.height * PRINT_UNITS) / CSS_UNITS) + 'pt; }' +
    84. '}' +
    85. '@media print {' +
    86. 'body { margin: 0 }' +
    87. '#print-canvas { page-break-before: avoid; page-break-after: always; page-break-inside: avoid; display: block }' +
    88. 'body > *:not(#print-container) { display: none; }' +
    89. '}'+
    90. '@media screen {' +
    91. 'body { margin: 0 }' +
    92. '}'
    93. return win;
    94. })
    95. })
    96. .then(function(win) {
    97. var allPages = [];
    98. for ( var pageNumber = 1; pageNumber <= pdfDoc.numPages; ++pageNumber ) {
    99. if ( pageNumberOnly !== undefined && pageNumberOnly.indexOf(pageNumber) === -1 )
    100. continue;
    101. allPages.push(
    102. pdfDoc.getPage(pageNumber)
    103. .then(function(page) {
    104. var viewport = page.getViewport({ scale: 1 });
    105. var printCanvasElt = printContainerElement.appendChild(win.document.createElement('canvas'));
    106. printCanvasElt.setAttribute('id', 'print-canvas')
    107. printCanvasElt.width = (viewport.width * PRINT_UNITS);
    108. printCanvasElt.height = (viewport.height * PRINT_UNITS);
    109. return page.render({
    110. canvasContext: printCanvasElt.getContext('2d'),
    111. transform: [ // Additional transform, applied just before viewport transform.
    112. PRINT_UNITS, 0, 0,
    113. PRINT_UNITS, 0, 0
    114. ],
    115. viewport: viewport,
    116. intent: 'print'
    117. }).promise;
    118. })
    119. );
    120. }
    121. Promise.all(allPages)
    122. .then(function() {
    123. win.focus(); // Required for IE
    124. if (win.document.queryCommandSupported('print')) {
    125. win.document.execCommand('print', false, null);
    126. } else {
    127. win.print();
    128. }
    129. removePrintContainer();
    130. })
    131. .catch(function(err) {
    132. removePrintContainer();
    133. emitEvent('error', err);
    134. })
    135. })
    136. }
    137. this.renderPage = function(rotate) {
    138. if ( pdfRender !== null ) {
    139. if ( canceling )
    140. return;
    141. canceling = true;
    142. pdfRender.cancel().catch(function(err) {
    143. emitEvent('error', err);
    144. });
    145. return;
    146. }
    147. if ( pdfPage === null )
    148. return;
    149. var pageRotate = (pdfPage.rotate === undefined ? 0 : pdfPage.rotate) + (rotate === undefined ? 0 : rotate);
    150. var scale = canvasElt.offsetWidth / pdfPage.getViewport({ scale: 1 }).width * (window.devicePixelRatio || 1);
    151. var viewport = pdfPage.getViewport({ scale: scale, rotation:pageRotate });
    152. emitEvent('page-size', viewport.width, viewport.height, scale);
    153. canvasElt.width = viewport.width;
    154. canvasElt.height = viewport.height;
    155. pdfRender = pdfPage.render({
    156. canvasContext: canvasElt.getContext('2d'),
    157. viewport: viewport
    158. });
    159. annotationLayerElt.style.visibility = 'hidden';
    160. clearAnnotations();
    161. var viewer = {
    162. scrollPageIntoView: function(params) {
    163. emitEvent('link-clicked', params.pageNumber)
    164. },
    165. };
    166. var linkService = new PDFLinkService();
    167. linkService.setDocument(pdfDoc);
    168. linkService.setViewer(viewer);
    169. pendingOperation = pendingOperation.then(function() {
    170. var getAnnotationsOperation =
    171. pdfPage.getAnnotations({ intent: 'display' })
    172. .then(function(annotations) {
    173. PDFJS.AnnotationLayer.render({
    174. viewport: viewport.clone({ dontFlip: true }),
    175. div: annotationLayerElt,
    176. annotations: annotations,
    177. page: pdfPage,
    178. linkService: linkService,
    179. renderInteractiveForms: false
    180. });
    181. });
    182. var pdfRenderOperation =
    183. pdfRender.promise
    184. .then(function() {
    185. annotationLayerElt.style.visibility = '';
    186. canceling = false;
    187. pdfRender = null;
    188. })
    189. .catch(function(err) {
    190. pdfRender = null;
    191. if ( err instanceof PDFJS.RenderingCancelledException ) {
    192. canceling = false;
    193. this.renderPage(rotate);
    194. return;
    195. }
    196. emitEvent('error', err);
    197. }.bind(this))
    198. return Promise.all([getAnnotationsOperation, pdfRenderOperation]);
    199. }.bind(this));
    200. }
    201. this.forEachPage = function(pageCallback) {
    202. var numPages = pdfDoc.numPages;
    203. (function next(pageNum) {
    204. pdfDoc.getPage(pageNum)
    205. .then(pageCallback)
    206. .then(function() {
    207. if ( ++pageNum <= numPages )
    208. next(pageNum);
    209. })
    210. })(1);
    211. }
    212. this.loadPage = function(pageNumber, rotate) {
    213. pdfPage = null;
    214. if ( pdfDoc === null )
    215. return;
    216. pendingOperation = pendingOperation.then(function() {
    217. return pdfDoc.getPage(pageNumber);
    218. })
    219. .then(function(page) {
    220. pdfPage = page;
    221. this.renderPage(rotate);
    222. emitEvent('page-loaded', page.pageNumber);
    223. }.bind(this))
    224. .catch(function(err) {
    225. clearCanvas();
    226. clearAnnotations();
    227. emitEvent('error', err);
    228. });
    229. }
    230. this.loadDocument = function(src) {
    231. pdfDoc = null;
    232. pdfPage = null;
    233. emitEvent('num-pages', undefined);
    234. if ( !src ) {
    235. canvasElt.removeAttribute('width');
    236. canvasElt.removeAttribute('height');
    237. clearAnnotations();
    238. return;
    239. }
    240. // wait for pending operation ends
    241. pendingOperation = pendingOperation.then(function() {
    242. var loadingTask;
    243. if ( isPDFDocumentLoadingTask(src) ) {
    244. if ( src.destroyed ) {
    245. emitEvent('error', new Error('loadingTask has been destroyed'));
    246. return
    247. }
    248. loadingTask = src;
    249. } else {
    250. loadingTask = createLoadingTask(src, {
    251. onPassword: function(updatePassword, reason) {
    252. var reasonStr;
    253. switch (reason) {
    254. case PDFJS.PasswordResponses.NEED_PASSWORD:
    255. reasonStr = 'NEED_PASSWORD';
    256. break;
    257. case PDFJS.PasswordResponses.INCORRECT_PASSWORD:
    258. reasonStr = 'INCORRECT_PASSWORD';
    259. break;
    260. }
    261. emitEvent('password', updatePassword, reasonStr);
    262. },
    263. onProgress: function(status) {
    264. var ratio = status.loaded / status.total;
    265. emitEvent('progress', Math.min(ratio, 1));
    266. }
    267. });
    268. }
    269. return loadingTask.promise;
    270. })
    271. .then(function(pdf) {
    272. pdfDoc = pdf;
    273. emitEvent('num-pages', pdf.numPages);
    274. emitEvent('loaded');
    275. })
    276. .catch(function(err) {
    277. clearCanvas();
    278. clearAnnotations();
    279. emitEvent('error', err);
    280. })
    281. }
    282. annotationLayerElt.style.transformOrigin = '0 0';
    283. }
    284. return {
    285. createLoadingTask: createLoadingTask,
    286. PDFJSWrapper: PDFJSWrapper,
    287. }
    288. }

  • 相关阅读:
    分布式架构在云计算平台中的应用及优缺点
    被问到: http 协议和 https 协议的区别怎么办?别慌,这篇文章给你答案
    CentOS7安装部署CDH6.2.1
    C++ Builder 6.0 消息重载的处理
    uniCloud开发公众号:三、生成带参数二维码
    CASAIM自动激光3D测量系统助力海外家电组装企业IQC来料检测装配尺寸测量
    NLP预训练模型-GPT-3
    安装Rocky 9
    uniapp如何实现返回上一级页面并传值刷新
    JAVA主要API
  • 原文地址:https://blog.csdn.net/weixin_40444253/article/details/133694827