background

Increased image preview before the demo, so this afternoon after finish were suddenly thought of PDF online preview can also do, start, start to check a lot of tutorials, I found a lot of people are talking about PDF. Js this library, this is, of course, no problem, PDF. Js can indeed very perfect PDF online preview the process of implementation, However, I felt that it was not elegant to go directly into it, so I looked for a ready-made component, and found that vue-PDF was not as powerful as the original one, for example, it does not support PDF text copying, and printing will be messy, but I felt that it was enough to meet my needs. This note takes you step by step, from a basic demo to a usable level, and ends with a list of problems and solutions that you might encounter in the actual process of using it.

Installation:

Vue-pdf is installed just like any other vUE component. Open the command line and type:

npm install --save vue-pdf
Copy the code

Pay attention to the path. Don’t pull out a terminal installation in the desktop, this direct call back to relearn Vue.

Vue-pdf First Experience:

Once installed, using vue-PDF is very simple, just like any other component.

First we need to introduce this component:

<script>
import pdf from 'vue-pdf'
export default {
  components:{
      pdf
  },
  data(){
      return {
          url:"http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf",}}</script>   
Copy the code

Then use vue-PDF on the page, just add the tag:

<template>
<div>
  <pdf 
    ref="pdf"
    :src="url">
  </pdf>
</div>
</template>
Copy the code

Restart your project, visit this screen, and you will most likely find that the PDF has been successfully displayed on your screen. There is nothing wrong with that, but just as you are about to pick up a cigarette, light it, and enjoy your masterpiece of success to the comforting accompanine of The Beautiful Solo river, you will discover, oh, why is there only one page, when glasses touch and the world is filled with the sound of dreams breaking.

So, just to get started, if your PDF is only one page, this is fine, but when we have a PDF of many pages, you’ll find that it doesn’t work. So, next, let’s look at how to make it show multiple pages.

Vue-pdf is on the rise:

Actually, if you want to display multiple pages, it’s not that complicated, you just display one page at a time, and I’m just going to do a V-for loop, and I’m just going to do it, and it’s pretty straightforward.

Page code:

<template>
	<div>
	<pdf  v-for="i in numPages" :key="i"  :src="url" :page="i"></pdf>	
	</div>
</template>

<script>
	import pdf from 'vue-pdf'
	export default {
		components: {
			pdf
		},
		data(){
			 return{
				    url: ' '.numPages:1,}},mounted: function() {
		  this.getNumPages("http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf")},methods: {
			getNumPages(url) {
				var loadingTask = pdf.createLoadingTask(url)
				loadingTask.then(pdf= > {
					this.url = loadingTask
					this.numPages = pdf.numPages
				}).catch((err) = > {
					console.error('PDF loading failed')})},}</script>

Copy the code

Each attribute:

  • Url: Indicates the path of the PDF file, which can be a local or online path.
  • NumPages: Total pages of the PDF file.

GetNumPages calculates the total number of pages, incidentally assigning values to the URL and numPages.

The only thing that needs your attention is this:

this.getNumPages("http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf")
Copy the code

In Mounted, you can write it wherever you want. For example, if you request a PDF url from the front end and the back end returns a PDF URL, you can write it wherever you want.

Vue-pdf On the road:

A lot of people see this. Right here. Right here? Just in case my PDF is a thousand pages long and my browser still hasn’t cracked open, what I want is the feeling of flipping through pages on a tipsy afternoon. Can you give it to me?

I can’t. No, I promise.

<template>
	<div>
		<div class="tools">
			<bk-button :theme="'default'" type="submit" :title='Base button' @click.stop="prePage" class="mr10">The previous page</bk-button>
			<bk-button :theme="'default'" type="submit" :title='Base button' @click.stop="nextPage" class="mr10">The next page</bk-button>
			<div class="page">{{pageNum}}/{{pageTotalNum}} </div>
			<bk-button :theme="'default'" type="submit" :title='Base button' @click.stop="clock" class="mr10">clockwise</bk-button>
			<bk-button :theme="'default'" type="submit" :title='Base button' @click.stop="counterClock" class="mr10">counterclockwise</bk-button>
		</div>
		<pdf ref="pdf" 
		:src="url" 
		:page="pageNum"
		:rotate="pageRotate"  
		@progress="loadedRatio = $event"
		@page-loaded="pageLoaded($event)" 
		@num-pages="pageTotalNum=$event" 
		@error="pdfError($event)" 
		@link-clicked="page = $event">
		</pdf>
	</div>
</template>
Copy the code

Now, let’s talk about what these are.

Parameter description:

  • page: Indicates the number of pages currently displayed. For example, the first page=1
  • rotate: Rotation Angle. For example, 0 means no rotation, +90, -90 means horizontal rotation.
  • progress: The loading progress of the current page. The range is 0 to 1. The value 1 indicates that the current page has been fully loaded.
  • page-loaded: the callback function for the page to load successfully.
  • num-pages: the total number of pages
  • error: load error callback
  • link-clicked: Link in standalone PDF will trigger.

Other:

  • Print is the print function. Note: Garbled characters appear in Chrome, depending on the font.

Here, the js code goes:

<script> import pdf from 'vue-pdf' export default { name: 'Home', components: { pdf }, data() { return { url: "Http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf", pageNum: 1, pageTotalNum: 1, pageRotate: LoadedRatio: 0, curPageNum: 0, mounted: function() {}, methods: {// prePage() {var page = this.pageNum page = page > 1? this.pageTotalNum this.pageNum = page }, // nextPage() {var page = this.pageNum page = page < this.pageTotalNum? Page + 1: This. PageNum = page}, // turn the page clockwise by 90 degrees. Clock () {this.pagerotate += 90}, // turn the page 90 degrees counterclockwise. CounterClock () {this.pagerotate -= 90}, // pageLoaded(e) {this.curpagenum = e}, // some other callback functions. pdfError(error) { console.error(error) }, } } </script>Copy the code

Other SAO operation:

// Print all
pdfPrintAll() {
	this.$refs.pdf.print()
		},
// Print the specified section
pdfPrint() {
	this.$refs.pdf.print(100[1.2])},Copy the code

I will not post the specific style of what, these are not the point, can completely change their own like.

Finished product display:

Other issues and solutions:

How to load a local PDF file (updated 2020.4.27) :

Someone mentioned this problem in the comment section, I tried it at noon today, and it is totally ok, but we need to locally configure the lie-loader, otherwise webpack cannot compile PDF files, the configuration method is also very simple, create a vue.config.js file in the root directory of the project. I find that many people go directly to babel.config.js to configure it. This is not correct.

First installation file – loader:

npm install --save file-loader
Copy the code

Then add the following to vue.config.js:

module.exports = {
    chainWebpack: config= > {
        const fileRule = config.module.rule('file')
        fileRule.uses.clear()
        fileRule
            .test(/\.pdf|ico$/)
            .use('file-loader')
            .loader('file-loader')
            .options({
                limit: 10000,}}),publicPath: '/'
}
Copy the code

Then the url: require (“.. < img SRC = “/assets/1.pdf” style =” box-sizing: border-box; border-box: border-box; border-box: border-box; border-box: border-box; border-box: border-box; border-box: border-box; border-box: border-box; border-box: border-box; border-box: border-box; border-box: border-box; border-box: border-box; border-box: border-box; border-box: border-box; border-box: border-box; border-box: border-box;

Cross-domain issues:

Many online pdf.js will encounter cross-domain problems, this I actually applied to my own project today, because my server set cross-domain, so there is no cross-domain problems, if there is cross-domain need to modify your backend request header.

Print interface characters garbled:

I’ve come across this one, but when Google prints it, the preview screen actually turns into real squares, full of squares. This problem is caused by the use of custom fonts in your PDF. The specific solution is as follows:

First, find the file: node_modules/vue-pdf/ SRC/pdfjswrapper.js

According to the Github issue, the red ones are to be deleted and the green ones are to be added.

Address: github.com/FranckFreib…

According to my actual test, it can solve the problem of printing garbled code.

Thank you very much for reading here. Your support and attention are the motivation for me to keep on sharing with high quality.

The relevant code and documentation have been uploaded to my Github. Make sure you order a star

The long march is always love, give a star line

Hanshu’s development notes

Welcome to like, follow me, you have good fruit (funny)