Use pdf.js to display pdf files on web pages

In a recent project, PDF files need to be displayed online. In the past, Adobe PDF reader was used to open directly on the browser side. This requires the client to install this software. If it is not installed, it cannot be previewed online. In order to solve this problem, I finally decided to use pdf.js to implement the preview function.

 

1. Download PDF.js :

Download link: http://mozilla.github.io/pdf.js/

The downloaded compressed package contains two folders: build and web. Open viewer.html in the web folder, and you can see the preview effect of the PDF.

The previewed PDF file is compressed.tracemonkey-pldi-09.pdf located in the same directory as viewer.html.

The setting to load this file is: the DEFAULT_URL attribute of viewer.js in the same directory as viewer.html . Modifying the value of this attribute can preview different files, and both Chinese and English pdf files can be previewed successfully .

 

2. Function use :

The key to using pdf.js to display a pdf file on a web page is to open viewer.html, that is, to open an html on a web page. There are at least two or three methods available:

a, a tag: <a href="PDFJS\web\viewer.html">Use pdf.js to display pdf files</>

b、window.open:window.open("PDFJS\web\viewer.html");

c、iframe:<iframe  src="PDFJS\web\viewer.html" />

 

3. Preview server-side files on the client side: use file streams to solve

Take the situation I use this time as an example, the iframe I use to display:

Step 1: Set the request path of the iframe :

var src="pdfjs/web/viewer.html?file=/testWeb/fileRouter!openDocInPdf.action";

 

illustrate:

a. pdfjs/web/viewer.html must be brought, there is nothing to say

 

b. If you request a file from the server, you must use the file keyword to tell pdf.js that this is a file stream. How did I know? Baidu + source code. When I saw the demo on the Internet, I said to use this keyword. I also wondered how you knew to use this keyword, so I went to the source code. During the tracking process, I found that there is such a sentence in the method of webViewerInitialized() of viewer.js :

file = 'file' in params ? params.file : appConfig.defaultUrl;

This is obvious, if you don't have a file I'll use the default. So the file keyword must be used.

 

c. testWeb is my project name. When requesting action here, you must add: / project name. If you don't do this, you will report a 404 (at least in my case).

What a 404? ? Suppose my project access path is: http://127.0.0.1:8080/testWeb,

If it is written as file=/testWeb/fileRouter!openDocInPdf.action, (the writing method mentioned above)

Then the request path is: http://127.0.0.1:8080/testWeb/fileRouter!openDocInPdf.action, correct

If written as file=fileRouter!openDocInPdf.action (without adding /testWeb)

Then the request path: http://127.0.0.1:8080/fileRouter!openDocInPdf.action (404)

Or write: file=/fileRouter!openDocInPdf.action (without adding testWeb, only adding /)

Request path: http://127.0.0.1:8080/fileRouter!openDocInPdf.action (404)

 

Step 2: Make a request using an iframe :

$("body").append("<iframe  width=\"100%\" height=\"100%\" src='"+src+"' />");

 

Step 3: Action request :

HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("application/pdf");
FileInputStream in = new FileInputStream(pdfFile);
OutputStream out = response.getOutputStream();

byte[] b = new byte[1024];
while ((in.read(b)) != -1) {
	out.write(b);
}
out.flush();
in.close();
out.close();

Of course, in practical applications, the problem with parameters is often involved, which is the fourth point to be mentioned later.

 

4. File request with parameters :

URLs with parameters are usually written like this: fileRouter!openDocInPdf.action?id=123,

As usual, it should be: var src="pdfjs/web/viewer.html?file=/testWeb/fileRouter!openDocInPdf.action?id=123";

Following this path to request the final request link will become: http://127.0.0.1:8080/testWeb/fileRouter!openDocInPdf.action?id, such a request path will inevitably report an error, so why is it like this? Or the webViewerInitialized() of viewer.js, the code for processing the link is like this:

var appConfig = PDFViewerApplication.appConfig;
var file = void 0;
var queryString = document.location.search.substring(1);
//alert(queryString);//Result: file=/testWeb/fileRouter!openDocInPdf.action?id=123,
var params = (0, _ui_utils.parseQueryString)(queryString);
//alert(params.file);//Result: testWeb/fileRouter!openDocInPdf.action?id
file = 'file' in params ? params.file : appConfig.defaultUrl;
validateFileURL(file);

 Looking at the results, you can see that the problem lies in the fourth line. The parseQueryString method in the fourth line is as follows:

function parseQueryString(query) {
  var parts = query.split('&');
  var params = Object.create(null);
  for (var i = 0, ii = parts.length; i < ii; ++i) {
    var param = parts [i] .split ('=');
    var key = param [0] .toLowerCase ();
    var value = param.length > 1 ? param[1] : null;
    params[decodeURIComponent(key)] = decodeURIComponent(value);
  }
  return params;
}

Now you should know why the request link becomes like that.

 

In fact, there is a problem with the above example, and you may have found it carefully, that is the problem of requesting links: var src="pdfjs/web/viewer.html?file=/testWeb/fileRouter!openDocInPdf.action?id=123", There cannot be more than one ? in a url, only the first parameter is used? All others use &, what will happen if the request is replaced with &, will there be no problem? ?

Suppose the request looks like this: var src="pdfjs/web/viewer.html?file=/testWeb/fileRouter!openDocInPdf.action&id=123", the execution result of webViewerInitialized() of viewer.js is:

var appConfig = PDFViewerApplication.appConfig;
var file = void 0;
var queryString = document.location.search.substring(1);
//alert(queryString);//结果:file=/testWeb/fileRouter!openDocInPdf.action&id=123
var params = (0, _ui_utils.parseQueryString)(queryString);
//alert(params.file);//Result: testWeb/fileRouter!openDocInPdf.action
file = 'file' in params ? params.file : appConfig.defaultUrl;
validateFileURL(file);

In the end it becomes no parameters.

 

Next , I think there are at least two solutions :

The first one : split("=") plays a key role in the parseQueryString() method. When there are multiple equal signs except the first one, the other ones have not been eliminated, so if I guarantee this url There is only an equal sign in file= here, so it can be changed to:

var src = "pdfjs/web/viewer.html?file="+encodeURIComponent("/testWeb/fileRouter!openDocInPdf.action?id=123");

This will become: file=%2FtestWeb%2FfileRouter!openDocInPdf.action%3Fid%3D123

The final request link is: http://127.0.0.1:8080/testWeb/fileRouter!openDocInPdf.action?id=123, this kind of request is correct.

 

The second: change the processing method, artificially define the value in the file :

Change the code that handles parameters in webViewerInitialized() to:

  var appConfig = PDFViewerApplication.appConfig;
  var file = void 0;
  var queryString = document.location.search.substring(1);
  /* Comment out the original parameter handling method
  var params = (0, _ui_utils.parseQueryString)(queryString);
  file = 'file' in params ? params.file : appConfig.defaultUrl;
  */
  //Use the following code to process
  if(queryString.split("file2=").length>0){
  	file = queryString.split("file2=")[1];
  }else{
  	file = appConfig.defaultUrl;
  }
  validateFileURL(file);

Then change the src of the iframe to: var src="pdfjs/web/viewer.html?file2=/testWeb/fileRouter!openDocInPdf.action?id=123";

Such a request would become: http://127.0.0.1:8080/testWeb/fileRouter!openDocInPdf.action?id=123

So far, the problem with parameters is solved.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326224697&siteId=291194637