How to use PDF.js in your project
This time I will show you how to use PDF.js in the project, and what are the precautions for using PDF.js in the project. The following is a practical case, let's take a look.
It was once used when developing a policy preview on WeChat. Since the Android mobile browser does not support parsing PDF, PDF.js was used to parse the PDF and display it.
pdf.js is a technical prototype mainly used to display PDF documents on the HTML5 platform without any local technical support.
Online demo address: http://mozilla.github.com/pdf.js/web/viewer.html
PDF.js can be downloaded from the official website Address: http://mozilla. github.io/pdf.js/
The directory structure after decompression is:
The build directory is the core file of PDF.js.
The web directory is the configuration and display file of PDF.js.
viewer.html is responsible for displaying PDF, and viewer.js is the file responsible for configuration. In viewer.js:
where var DEFAULT_URL is the default parsed PDF file and can be replaced.
How to use pdf.js (1):
For simple use that only displays one PDF file, you only need to configure the
default path That's fine, but in many cases this method doesn't meet development needs.
How to use pdf.js (2):
Pass ?file=test.pdf after the address bar to complete the modification of the default path
http://localhost:8080/pdfjs/web/viewer.html?file=test.pdf //It’s best not to transmit Chinese. I haven’t tried it specifically
The test.pdf here can be taken as a relative path to the viewer.html (the absolute path of the entire server will also work)
How to use pdf.js (3):
Modify the path of the PDF by assigning a value to window.localStorage.pdf (after testing, it is best to write the path of the http protocol)
For example:
window.localStorage.pdf= 'http://localhost:8080/pdf/20140620/000000091534588.pdf'; window.location.href=basePath+"jsTool/openPDF/web/viewer.html";
How to use pdf.js (4):
Excerpted from (official website example) http://mozilla.github.io/pdf.js/examples/
1. The page introduces pdf.js.
2. Use PDFJS.getDocument('helloworld.pdf') method to load the PDF file to be opened.
3. Process subsequent methods through PDFJS.getDocument('helloworld.pdf').then(function(pdf){// you can now use *pdf* here}); then
4. pdf.getPage(1).then(function(page){// you can now use *page* here}); Load the first page of PDF
5. Through h5 canvas exhibit.
var scale = 1.5; var viewport = page.getViewport(scale); var canvas = document.getElementById('the-canvas'); var context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; page.render(renderContext);
Complete example:
//引入pdf.js之后 var url = '//cdn.mozilla.net/pdfjs/helloworld.pdf'; //加载核心文件 PDFJS.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js'; var loadingTask = PDFJS.getDocument(url); loadingTask.promise.then(function(pdf) { console.log('PDF loaded'); var pageNumber = 1; pdf.getPage(pageNumber).then(function(page) { console.log('Page loaded'); var scale = 1.5; var viewport = page.getViewport(scale); var canvas = document.getElementById('the-canvas'); var context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; var renderTask = page.render(renderContext); renderTask.then(function () { console.log('Page rendered'); }); }); }, function (reason) { console.error(reason); });
Click to view page by page:
Page:
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script> <h1>PDF.js Previous/Next example</h1> <p> <button id="prev">Previous</button> <button id="next">Next</button> <span>Page: <span id="page_num"></span> / <span id="page_count"></span></span> </p> <canvas id="the-canvas"></canvas>
js:
var url = '//cdn.mozilla.net/pdfjs/tracemonkey.pdf'; PDFJS.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js'; var pdfDoc = null, pageNum = 1, pageRendering = false, pageNumPending = null, scale = 0.8, canvas = document.getElementById('the-canvas'), ctx = canvas.getContext('2d'); function renderPage(num) { pageRendering = true; pdfDoc.getPage(num).then(function(page) { var viewport = page.getViewport(scale); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: ctx, viewport: viewport }; var renderTask = page.render(renderContext); renderTask.promise.then(function() { pageRendering = false; if (pageNumPending !== null) { // New page rendering is pending renderPage(pageNumPending); pageNumPending = null; } }); }); document.getElementById('page_num').textContent = pageNum; } function queueRenderPage(num) { if (pageRendering) { pageNumPending = num; } else { renderPage(num); } } function onPrevPage() { if (pageNum <= 1) { return; } pageNum--; queueRenderPage(pageNum); } document.getElementById('prev').addEventListener('click', onPrevPage); function onNextPage() { if (pageNum >= pdfDoc.numPages) { return; } pageNum++; queueRenderPage(pageNum); } document.getElementById('next').addEventListener('click', onNextPage); PDFJS.getDocument(url).then(function(pdfDoc_) { pdfDoc = pdfDoc_; document.getElementById('page_count').textContent = pdfDoc.numPages; renderPage(pageNum); });
The functions of this plug-in are very powerful. There are many downloads (downloads are not available on mobile phones) or page jump functions. If you don’t want customers to view them, you can hide or delete the corresponding buttons in viewer.html
Additional point: Viewer consumes system resources when parsing and rendering PDF, especially CPU resources. I don’t know if it is because my notebook configuration is low. While the page is loading and waiting, the IE process consumes 50-60% of CPU resources are lost. Clicking on the page turning operation or changing the window size of IE will trigger the viewer to re-parse and render the PDF. Sometimes moving a program window (such as a txt) blocking it on the IE front end will also cause re-rendering, but it is not triggered every time for unknown reasons.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to use the Installation plug-in in actual projects
Using vue2.0 boostrap in the case
The above is the detailed content of How to use PDF.js in your project. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
