Displaying Pdf in Javafx using PDFJS library in Webview

≡放荡痞女 提交于 2019-12-11 07:53:31

问题


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:-


回答1:


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.



来源:https://stackoverflow.com/questions/53819001/displaying-pdf-in-javafx-using-pdfjs-library-in-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!