C:blanc
Published
June 8 2022
Blog JavaScript

View the PDF in your phone's browser without downloading it.

  • このエントリーをはてなブックマークに追加

Introduction.

When I open a PDF file on my phone, it is downloaded to my device once.
To view a PDF file in your phone's browser without downloading it, use the Javascript library PDF.js.
PDF.js

Download PDF.js

The latest version is no longer compatible with older browsers, so download v2.4.456 from
https://github.com/mozilla/pdf.js/releases/tag/v2.4.456
pdfjs-2.4.456-es5-dist.zip in Assets at the bottom of the page.

Also, the latest version was not easy to customize and the search function did not work with some PDF files. (This may be a problem on the PDF file side...)

Also, the latest version (v2.14.305), by golly, the pinch didn't work.
https://mozilla.github.io/pdf.js/web/viewer.html

treatment

I can't view it directly, so I moved it to Sites on my mac.
(I assume it's the same if you upload it to docker or a server)
http://localhost/pdfjs-2.4.456-es5-dist/web/viewer.html
It is now displayed. Surprisingly easy.
web/viewer.js
defaultUrl: {
    value: "compressed.tracemonkey-pldi-09.pdf",
    kind: OptionKind.VIEWER
},
PDF file is specified in viewer.js line 4550.

Japanese localization

To make it Japanese, simply add lang="ja" to the html tag.
web/viewer.html
<html lang="ja" dir="ltr" mozdisallowselectionprint>

Specify a PDF file to view

Delete the PDF file name "compressed.tracemonkey-pldi-09.pdf" on line 4550 of viewer.js.

Add the following Javascript code under <script src="viewer.js"></script>in viewer.html.
We will create a pdf directory and put the PDF file there.
web/viewer.js
defaultUrl: {
  value: "",
  kind: OptionKind.VIEWER
},
web/viewer.html
<script src="viewer.js"></script>

<script>
window.addEventListener('load', function() {
  PDFViewerApplication.open('../pdf/1.pdf');
  PDFViewerApplication.setTitle('タイトル');
}, false);
</script>
If you PHP viewer.html and rewrite it as follows, you can replace PDF files depending on queries and other parameters.
PDFViewerApplication.open(' <?= $file >');
PDFViewerApplication.setTitle(' <?= $title >');

finished product

https://blog.c-blanc.com/demo/blog/2/web/viewer.html
(We used Myna-chan's calendar for the PDF.)

It worked without the cmaps folder. (I haven't tested it specifically).
I only use locale.properties and ja folder in the locale directory as well.

At the end.

For production use, you will want to move viewer.html up one level. (Is it just me?)
In that case, simply rewrite the paths in viewer.html and viewer.js.

For Android, you may need Firefox ????.

PROFILE

C:blanc
I am a freelance programmer.
  • COMMENT

    Submitted. Comments will appear after approval.
  • あと150more characters