Pdf.js: How to display ("data:application/pdf;base64," + pdfData) in Viewer.html using PDF.js

Created on 18 Apr 2017  路  11Comments  路  Source: mozilla/pdf.js

Link to PDF file (or attach file here):

Configuration:

  • Web browser and its version: Chrome
  • Operating system and its version: Windows 7
  • PDF.js version: 2.0
  • Is an extension:

Steps to reproduce the problem:

  1. I am getting PDF bytes which I am converting to Convert.ToBase64String(PDFBytesData);
  2. The value I am getting something like this shown below
    ("JVBERi0xLjUKJVBERi0xLjUK..........."; // Base64 String from response shortened)

Queries:

  1. Please tell me how to bind this base64 string in (/pdf.js-master/web/viewer.html).
  2. How to pass parameter with base64string something like this as shown below:

iframe.src = "data:application/pdf;base64," + pdfbytesData + '#search=' + $('#hidden-searchKey').val().trim() + "&phrase=true";

What is the expected behavior? (add screenshot)
I am getting empty Viewer.html. The PDF is not getting loaded with base64 string.
What went wrong? (add screenshot)

Link to a viewer (if hosted on a site other than mozilla.github.io/pdf.js or as Firefox/Chrome extension):

Most helpful comment

Yes it supports base64,
1.Set var DEFAULT_URL = ''; in viewer.js
2.Convert base64 to Uint array
`pdfData = base64ToUint8Array(base64);

function base64ToUint8Array(base64) {
var raw = atob(base64);
var uint8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}

});`

3.Open by
PDFViewerApplication.open(pdfData);

All 11 comments

Refer to https://github.com/mozilla/pdf.js/wiki/Frequently-Asked-Questions#can-i-specify-a-different-pdf-in-the-default-viewer for the answer regarding base64 strings. There is also an example at https://github.com/mozilla/pdf.js/blob/master/examples/learning/helloworld64.html. Closing as answered.

I guess you didn't get what i exactly want. I want to load base64string in Viewer.html .

The viewer is not designed with that in mind. It is specific for the usage in Firefox (and extensions), so if you want that, you'll have to implement that functionality in the viewer yourself (using the examples as reference).

@timvandermeij can it support chinese?today i have use pdf.js in the same way,but my preview result is blank where there is chinese.the under is my code,do you know why myresult is like this,thanks.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>'Hello, world!' base64 example</title>
</head>
<body>

<h1>'Hello, world!' example</h1>

<canvas id="the-canvas" style="border:1px  solid black"></canvas>

<!--
<script src="../../node_modules/pdfjs-dist/build/pdf.js"></script>
-->
<!--
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.487/pdf.js"></script>
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.487/pdf.min.js"></script>

<script id="script">
  // atob() is used to convert base64 encoded PDF to binary-like data.
  // (See also https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/
  // Base64_encoding_and_decoding.)
//  var pdfData = atob(
//    'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
//    'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
//    'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
//    'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
//    'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
//    'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
//    'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
//    'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
//    'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
//    'ZG9iagoKeHJlZgowIDYK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bnRTY2FsaW5nL0FwcERlZmF1bHQ+Pi9Q\nYWdlcyA1IDAgUj4+CmVuZG9iagoxMiAwIG9iago8PC9DcmVhdG9yKEphc3BlclJlcG9ydHMgTGli\ncmFyeSB2ZXJzaW9uIDUuNi4wKS9Qcm9kdWNlcihpVGV4dCAyLjEuNyBieSAxVDNYVCkvTW9kRGF0\nZShEOjIwMTcxMjI5MTE0OTE0KzA4JzAwJykvQ3JlYXRpb25EYXRlKEQ6MjAxNzEyMjkxMTQ5MTQr\nMDgnMDAnKT4+CmVuZG9iagp4cmVmCjAgMTMKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAxODc1\nIDAwMDAwIG4gCjAwMDAwMDIxNjMgMDAwMDAgbiAKMDAwMDAwMjYwNSAwMDAwMCBuIAowMDAwMDAw\nMDE1IDAwMDAwIG4gCjAwMDAwMDI3MjkgMDAwMDAgbiAKMDAwMDAwMjEyOCAwMDAwMCBuIAowMDAw\nMDAyMjUxIDAwMDAwIG4gCjAwMDAwMDI0NDIgMDAwMDAgbiAKMDAwMDAwMjc5MiAwMDAwMCBuIAow\nMDAwMDAyODQ2IDAwMDAwIG4gCjAwMDAwMDI4NzkgMDAwMDAgbiAKMDAwMDAwMjk4NCAwMDAwMCBu\nIAp0cmFpbGVyCjw8L1Jvb3QgMTEgMCBSL0lEIFs8NzM3YjNiYTEyZTQ3ZjE4MDdlYjE1NDA1NjMw\nMDQyYWI+PDRiMzVlN2ZlOWU0YTM4YWU3ZDJiY2E1MTgzNmQ2NWZmPl0vSW5mbyAxMiAwIFIvU2l6\nZSAxMz4+CnN0YXJ0eHJlZgozMTUyCiUlRU9GCg=='
  );

  //
  // The workerSrc property shall be specified.
  //
  pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.487/pdf.worker.min.js';

  // Opening PDF by passing its binary data as a string. It is still preferable
  // to use Uint8Array, but string or array-like structure will work too.
  pdfjsLib.getDocument({data: pdfData}).then(function getPdfHelloWorld(pdf) {
    // Fetch the first page.
    pdf.getPage(1).then(function getPageHelloWorld(page) {
      var scale = 1.5;
      var viewport = page.getViewport(scale);

      // Prepare canvas using PDF page dimensions.
      var canvas = document.getElementById('the-canvas');
      var context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;

      // Render PDF page into canvas context.
      var renderContext = {
        canvasContext: context,
        viewport: viewport
      };
      page.render(renderContext);
    });
  });
</script>

<hr>
<h2>JavaScript code:</h2>
<pre id="code"></pre>
<script>
  document.getElementById('code').textContent =
    document.getElementById('script').text;
</script>
</body>
</html>

The viewer is not designed with that in mind. It is specific for the usage in Firefox (and extensions), so if you want that, you'll have to implement that functionality in the viewer yourself (using the examples as reference).

Are you saying that viewer.html is not intended to be used as a container for binary PDF data, and that it's only purpose is to be used as a lousy plugin? According to the pdf.js documentation, as crappy and as incomplete as it is, (as far as API docs go) provides a small demo on how to use the viewer with a static PDF file. At this point, I will believe anything I read about pdf.js. Its API documentation completely fails to provide coding usage for rendering a binary PDF in viewer.html, among other things. I just want to be crystal clear about your answer, because if I cannot use viewer.html for a binary PDF then I am not going to waste another minute trying to figure out pdf.js viewer\binary method. Thanks.

I cannot use viewer.html for a binary PDF

@capegreg there is no such thing as a "binary PDF". If you want to display base64 encoded string you need to decode it yourself, since only few browsers can decode it. The base64 encoding and decoding is very inefficient operation (for servers and client) -- we don't believe supporting it will be beneficial for PDF.js.

iframe.src = "data:application/pdf;base64," + pdfbytesData +

Keep in mind that there is a limit in some browsers on length of URL, and this out of control of PDF.js

I cannot use viewer.html for a binary PDF

@capegreg there is no such thing as a "binary PDF". If you want to display base64 encoded string you need to decode it yourself, since only few browsers can decode it. The base64 encoding and decoding is very inefficient operation (for servers and client) -- we don't believe supporting it will be beneficial for PDF.js.

iframe.src = "data:application/pdf;base64," + pdfbytesData +

Keep in mind that there is a limit in some browsers on length of URL, and this out of control of PDF.js

Thanks yurydelendik. I am decoding it. I just need to know how to implement the viewer.html. My binary pdf is currently rendered in a Canvas element, but I guess that's not supported with viewer.html. I suspect that all I need to do is assign the pdfData to the iframe src, as shown in your iframe.src example.

// data is already decoded
var pdfData = data;
// get my iframe document and set the src
iframe.src = "data:application/pdf;base64," + pdfData;

// don't need part this anymore
var pdfjsLib = window['pdfjs-dist/build/pdf'];
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.550/pdf.worker.min.js';
var loadingTask = pdfjsLib.getDocument({data: pdfData});
loadingTask.promise.then(function(pdf) {
var pageNumber = 1;
pdf.getPage(pageNumber).then(function(page) {
var scale = 0.9;
var viewport = page.getViewport(scale);
// Prepare canvas using PDF page dimensions
var canvas = document.getElementById('trimCanvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.then(function () {
console.log('Page rendered');
});
});
}, function (reason) {
// PDF loading error
console.error(reason);
});

Yes it supports base64,
1.Set var DEFAULT_URL = ''; in viewer.js
2.Convert base64 to Uint array
`pdfData = base64ToUint8Array(base64);

function base64ToUint8Array(base64) {
var raw = atob(base64);
var uint8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}

});`

3.Open by
PDFViewerApplication.open(pdfData);

Yes it supports base64,
1.Set var DEFAULT_URL = ''; in viewer.js
2.Convert base64 to Uint array
`pdfData = base64ToUint8Array(base64);

function base64ToUint8Array(base64) {
var raw = atob(base64);
var uint8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}

});`

3.Open by
PDFViewerApplication.open(pdfData);

it works well for the pc and android , but comes to ios, it cant't be totally showed on the ios browser. I can't resolve it 锛侊紒锛侊紒锛侊紒锛侊紒锛侊紒锛侊紒

iframe.src = "data:application/pdf;base64," + pdfbytesData +

Keep in mind that there is a limit in some browsers on length of URL, and this out of control of PDF.js

This is not supported by Edge! Sample: https://stackblitz.com/edit/typescript-pf9kxx?file=index.html

This is actually the reason, I want to use pdf.js. To display inlined pdf data....

Just for the record: pdf.js is able to display PDF files encoded as base64 strings. Maybe the problem of @kakaluote444 is that the string itself was buggy. You one-line base64 string isn't really base64. It contains carriage returns (\n), line feeds (\a), and forward slashes (/).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Richard-Mlynarik picture Richard-Mlynarik  路  32Comments

jonasyuandotcom picture jonasyuandotcom  路  29Comments

soa-x picture soa-x  路  174Comments

BadFriend picture BadFriend  路  38Comments

Vanuan picture Vanuan  路  34Comments