前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【黄啊码】vue-pdf预览时无法显示印章和中文字体或者乱码(简单粗暴)

【黄啊码】vue-pdf预览时无法显示印章和中文字体或者乱码(简单粗暴)

作者头像
黄啊码
发布2022-09-08 15:06:27
2.4K0
发布2022-09-08 15:06:27
举报
文章被收录于专栏:黄啊码【CSDN同名】

看了网上的教程了吧,不知道如何下手了吧,啊码已经跳了一次坑了,这次我帮你填坑。

使用vue-pdf进行pdf的预览,但是此种方法并不能预览带签章的pdf,尝试了网上提供的多种方法均不能实现pdf带签章的渲染

首先你需要安装  npm install --save vue-pdf

很多人引用的时候可能会出现只能展示pdf第一页的情况,这时候你可以看下官网的说明

官网链接www.npmjs.com/package/vue…

解决印章不显示:

找到我们安装好的 vue-pdf 安装包里的 pdf.worker.js 文件,如图展示路径

找到文件后注释掉此行代码:_this3.setFlags(_util.AnnotationFlag.HIDDEN) 如下放代码

 将这行注释:this.setFlags(_util.AnnotationFlag.HIDDEN);

解决中文不展示:

原因:正常情况,不会显示中文的问题。一般出问题的都是票据、合同之类的pdf,中文字体库没加载或加载失败,我们直接给它手动安排

cMapUrl: 'https://unpkg.com/pdfjs-dist@2.0.943/cmaps/'

以下是前端代码:

代码语言:javascript
复制
this.filetype = 'pdf'
            this.file_url = pdf.createLoadingTask({
            'url':this.webapi+file_url,
            cMapUrl: 'https://unpkg.com/pdfjs-dist@2.0.943/cmaps/',
            cMapPacked: true,
          })

 啊码的代码比较简单,没有那么多的杂七杂八,照抄就好了。

解决乱码:

如果遇到乱码的情况,额,写那么多我感觉只会误导你们,把vue-pdf/src/pdfjsWrapper.js中的这个文件给我改了,直接抄,不用给它面子

代码语言:javascript
复制
import { PDFLinkService } from 'pdfjs-dist/es5/web/pdf_viewer';

var pendingOperation = Promise.resolve();

export default function(PDFJS) {

	function isPDFDocumentLoadingTask(obj) {

		return typeof(obj) === 'object' && obj !== null && obj.__PDFDocumentLoadingTask === true;
		// or: return obj.constructor.name === 'PDFDocumentLoadingTask';
	}

	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');

		// source.verbosity = PDFJS.VerbosityLevel.INFOS;
		// source.pdfBug = true;
		// source.stopAtErrors = true;

		if ( options && options.withCredentials )
			source.withCredentials = options.withCredentials;

		var loadingTask = PDFJS.getDocument(source);
		loadingTask.__PDFDocumentLoadingTask = true; // since PDFDocumentLoadingTask is not public

		if ( options && options.onPassword )
			loadingTask.onPassword = options.onPassword;

		if ( options && options.onProgress )
			loadingTask.onProgress = options.onProgress;

		return loadingTask;
	}


	function PDFJSWrapper(canvasElt, annotationLayerElt, emitEvent) {

		var pdfDoc = null;
		var pdfPage = null;
		var pdfRender = null;
		var canceling = false;

		canvasElt.getContext('2d').save();

		function clearCanvas() {

			canvasElt.getContext('2d').clearRect(0, 0, canvasElt.width, canvasElt.height);
		}

		function clearAnnotations() {

			while ( annotationLayerElt.firstChild )
				annotationLayerElt.removeChild(annotationLayerElt.firstChild);
		}

		this.destroy = function() {

			if ( pdfDoc === null )
				return;

			// Aborts all network requests and destroys worker.
			pendingOperation = pdfDoc.destroy();
			pdfDoc = null;
		}

		this.getResolutionScale = function() {

			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 printContainerElement = document.createElement('div');
			printContainerElement.setAttribute('id', 'print-container')
			

			function removePrintContainer() {
				printContainerElement.parentNode.removeChild(printContainerElement);
			}

			new Promise(function(resolve, reject) {

				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 = '';

				return pdfDoc.getPage(1)
				.then(function(page) {
					var viewport = page.getViewport({ scale: 1 });
					printContainerElement.appendChild(win.document.createElement('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; }' +
						'}' +

						'@media print {' +
							'body { margin: 0 }' +
							'#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(
						pdfDoc.getPage(pageNumber)
						.then(function(page) {

							var viewport = page.getViewport({ scale: 1 });

							var printCanvasElt = printContainerElement.appendChild(win.document.createElement('canvas'));
							printCanvasElt.setAttribute('id', 'print-canvas')
							printCanvasElt.width = (viewport.width * PRINT_UNITS);
							printCanvasElt.height = (viewport.height * PRINT_UNITS);

							return page.render({
								canvasContext: printCanvasElt.getContext('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')) {
						win.document.execCommand('print', false, null);
						} else {
						win.print();
						}
						removePrintContainer();
				})
				.catch(function(err) {

					
					removePrintContainer();
					emitEvent('error', err);
				})
			})
		}

		this.renderPage = function(rotate) {
			if ( pdfRender !== null ) {

				if ( canceling )
					return;
				canceling = true;
				pdfRender.cancel().catch(function(err) {
					emitEvent('error', err);
				});
				return;
			}

			if ( pdfPage === null )
				return;

			var pageRotate = (pdfPage.rotate === undefined ? 0 : pdfPage.rotate) + (rotate === undefined ? 0 : rotate);

			var scale = canvasElt.offsetWidth / pdfPage.getViewport({ scale: 1 }).width * (window.devicePixelRatio || 1);
			var viewport = pdfPage.getViewport({ scale: scale, rotation:pageRotate });

			emitEvent('page-size', viewport.width, viewport.height, scale);

			canvasElt.width = viewport.width;
			canvasElt.height = viewport.height;

			pdfRender = pdfPage.render({
				canvasContext: canvasElt.getContext('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);
			linkService.setViewer(viewer);

			pendingOperation = pendingOperation.then(function() {

				var getAnnotationsOperation =
				pdfPage.getAnnotations({ intent: 'display' })
				.then(function(annotations) {

					PDFJS.AnnotationLayer.render({
						viewport: viewport.clone({ dontFlip: true }),
						div: annotationLayerElt,
						annotations: annotations,
						page: pdfPage,
						linkService: linkService,
						renderInteractiveForms: false
					});
				});

				var pdfRenderOperation =
				pdfRender.promise
				.then(function() {

					annotationLayerElt.style.visibility = '';
					canceling = false;
					pdfRender = null;
				})
				.catch(function(err) {

					pdfRender = null;
					if ( err instanceof PDFJS.RenderingCancelledException ) {

						canceling = false;
						this.renderPage(rotate);
						return;
					}
					emitEvent('error', err);
				}.bind(this))

				return Promise.all([getAnnotationsOperation, pdfRenderOperation]);
			}.bind(this));
		}


		this.forEachPage = function(pageCallback) {

			var numPages = pdfDoc.numPages;

			(function next(pageNum) {

				pdfDoc.getPage(pageNum)
				.then(pageCallback)
				.then(function() {

					if ( ++pageNum <= numPages )
						next(pageNum);
				})
			})(1);
		}


		this.loadPage = function(pageNumber, rotate) {

			pdfPage = null;

			if ( pdfDoc === null )
				return;

			pendingOperation = pendingOperation.then(function() {

				return pdfDoc.getPage(pageNumber);
			})
			.then(function(page) {

				pdfPage = page;
				this.renderPage(rotate);
				emitEvent('page-loaded', page.pageNumber);
			}.bind(this))
			.catch(function(err) {

				clearCanvas();
				clearAnnotations();
				emitEvent('error', err);
			});
		}

		this.loadDocument = function(src) {

			pdfDoc = null;
			pdfPage = null;

			emitEvent('num-pages', undefined);

			if ( !src ) {

				canvasElt.removeAttribute('width');
				canvasElt.removeAttribute('height');
				clearAnnotations();
				return;
			}

			// wait for pending operation ends
			pendingOperation = pendingOperation.then(function() {

				var loadingTask;
				if ( isPDFDocumentLoadingTask(src) ) {

					if ( src.destroyed ) {

						emitEvent('error', new Error('loadingTask has been destroyed'));
						return
					}

					loadingTask = src;
				} else {

					loadingTask = createLoadingTask(src, {
						onPassword: function(updatePassword, reason) {

							var reasonStr;
							switch (reason) {
								case PDFJS.PasswordResponses.NEED_PASSWORD:
									reasonStr = 'NEED_PASSWORD';
									break;
								case PDFJS.PasswordResponses.INCORRECT_PASSWORD:
									reasonStr = 'INCORRECT_PASSWORD';
									break;
							}
							emitEvent('password', updatePassword, reasonStr);
						},
						onProgress: function(status) {

							var ratio = status.loaded / status.total;
							emitEvent('progress', Math.min(ratio, 1));
						}
					});
				}

				return loadingTask.promise;
			})
			.then(function(pdf) {

				pdfDoc = pdf;
				emitEvent('num-pages', pdf.numPages);
				emitEvent('loaded');
			})
			.catch(function(err) {

				clearCanvas();
				clearAnnotations();
				emitEvent('error', err);
			})
		}

		annotationLayerElt.style.transformOrigin = '0 0';
	}

	return {
		createLoadingTask: createLoadingTask,
		PDFJSWrapper: PDFJSWrapper,
	}
}

最后,如果连例子都不会写,那咋办,拿去,直接抄

代码语言:javascript
复制
<template>
  <div>
    <div class="parent">
      <button @click="$refs.pdf.print()">打印</button>
      <pdf ref="pdf" :src="src" :page='currentPage' @progress='getProgress' @page-loaded="currentPage=$event" @loaded="loadPdfHandler"></pdf>
    </div>
    <el-pagination background layout="prev, pager, next" :page-size="1" :total="numPages" @current-change="changePage">
    </el-pagination>
  </div>
</template>

<script>
  import pdf from 'vue-pdf'
  const src = pdf.createLoadingTask('./static/bm.pdf');
  export default {
    data() {
      return {
        src,
        numPages: 100,
        currentPage: 1
      }
    },
    methods: {
      changePage(page) {
        this.currentPage = page;
      },

      getProgress(e) {
        console.log('加载进度:',e);
      },

      loadPdfHandler(){
        console.log('PDF加载完成啦');
      }
    },
    mounted() {
      this.src.then(pdf => {
        this.numPages = pdf.numPages;
      });
    },
    components: {
      pdf
    },
  }

</script>

<style scoped>
  .parent {
     1000px;
    margin: 0 auto;
  }
</style>

好了,问题解决了吧?退。。。退。。。退。。。朝【

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-07-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用vue-pdf进行pdf的预览,但是此种方法并不能预览带签章的pdf,尝试了网上提供的多种方法均不能实现pdf带签章的渲染
  • 解决印章不显示:
  • 解决中文不展示:
  • 解决乱码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档