简体   繁体   中英

Displaying Pdf in Javafx using PDFJS library in Webview

My goal is to display pdf documents in my JavaFX application. After researching I came across Mozilla's PDFJS library and found it pretty useful. What I'm doing is reading PDF file as a byte array from JAVA and calling the js code in Web view. Here is the code.

JAVA CODE

byte[] data = Files.readAllBytes(Paths.get("D:\\test\\test.pdf"));
    String base64 = Base64.getEncoder().encodeToString(data);   


    btn.setOnMouseClicked(e -> {
        String js = "openFileFromBase64('" + base64 + "')";
        engine.executeScript(js);
    });

Javascript Code

<script>
var openFileFromBase64 = function(data) {
    var arr = base64ToArrayBuffer(data);
    PDFViewerApplication.open(arr);
}

function base64ToArrayBuffer(base64) {
  var binary_string = window.atob(base64);
  var len = binary_string.length;
  var bytes = new Uint8Array(new ArrayBuffer(len));
  alert(len);
  for (var i = 0; i < len; i++)        {
      bytes[i] = binary_string.charCodeAt(i);
  }
  return bytes.buffer;
}

Problem

I'm able to render some pdf files just fine but I've some pdf files that won't open correctly. So I did some analysis and found following:-

  1. The problematic pdf files open correctly in adobe reader, firefox and edge browser.

  2. I thought the problem might be PDFJS library. So I tried placing my pdf file in WEB directory and opened viewer.html. To my surprise the pdf displayed correctly.

  3. I thought maybe some bytes are lost when I send data from Java to Javascript.So I printed number of bytes on each end and they match.

  4. Finally, I thought that java might be messing up the encoding. So I read the file from java and wrote the bytes to separate file and the file generated is correct.

I'm trying to understand if I overlooked something. Any suggestions are appreciated. Thanks in advance.

Here is how my pdf looks like after it is rendered:- 在此处输入图片说明

I had the same problem: No text would render properly in the JavaFX WebView using the current stable release of PDF.js as of today ( v2.0.943 ). Image based PDFs render properly.

Having a look at the PDF.js release notes, I found that v2.0.943 introduced lots of changes related to fonts and seem to have broken the font rendering in JavaFX.

The good news is that the current pre-release , v2.1.266 has some bugfixes regarding the handling of fonts and it fixes the text rendering problem in the JavaFX WebView.

If you don't feel confortable using a pre-release, you can use v1.10.100 , text rendering works with this version too, although I recommend using the latest version, because it seems to render the different fonts much better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM