0

我有一个 pdf 文件,它以 Hexa 字符串字节流的形式提供,例如:

"255044462D312E330D0A25E2E3CFD30D0A322030206F626A......"

(它是一个很长的字符串,所以我刚刚给出了格式)它是浏览器中可用的字符串格式。

我需要将其转换为十六进制格式,以便我可以通过将此输出流写入 pdf 文件来在 Web 浏览器中呈现 pdf。我需要知道是否有任何内置函数或任何方式可以在 Javascript 中实现。

我知道用 Java 实现这个功能很简单,但是我有一个ABAP后端只能获取这个字符串,而SAPUI5前端是一个基于 Javascript 的框架。

我通过编写一个简单的 java 程序来检查这个字节流的有效性,该程序生成 PDF 仅用于测试目的,如果数据正确的话:

public static void main(String[] args) {
  FileOutputStream fop = null;
  File file;
  file = new File("C:/Users/I074098/Desktop/Project Temps/test.pdf");
  fop = new FileOutputStream(file);
  // if file doesnt exists, then create it
  if (!file.exists()) {
    file.createNewFile();
  }
  //I manually added "(byte) 0x" in the above string and 
  //converted it to the following format, I skipped that conversion in this code
  byte[] contentInBytes = new byte[]{
    (byte) 0x25,(byte) 0x50,(byte) 0x44,(byte) 0x46, .....
  } 
  fop.write(contentInBytes);
    fop.flush();
    fop.close();
  } 

这会生成pdf。但我知道这是非常低效的,我不确定这一切都可以在 javascript 中完成。我做了很多搜索,但没有结果。我将不胜感激任何帮助。

问候, 里斯万

4

1 回答 1

2
   //  To IE Boat method is here,

        if (!window.btoa) {
    var tableStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var table = tableStr.split("");

    window.btoa = function (bin) {
    for (var i = 0, j = 0, len = bin.length / 3, base64 = []; i < len; ++i) {
    var a = bin.charCodeAt(j++), b = bin.charCodeAt(j++), c = bin.charCodeAt(j++);
    if ((a | b | c) > 255) throw new Error("String contains an invalid character");
    base64[base64.length] = table[a >> 2] + table[((a << 4) & 63) | (b >> 4)] +
    (isNaN(b) ? "=" : table[((b << 2) & 63) | (c >> 6)]) +
    (isNaN(b + c) ? "=" : table[c & 63]);
    }
    return base64.join("");
    };
    } 

      //script block
      // try this way  to open you pdf file like this in javascript hope it will help you.
        function hexToBase64(str)
          {
         return btoa(String.fromCharCode.apply(null,str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
          }

          var data=   hexToBase64("255044462D312E330D0A25E2E3CFD30D0A322030206F626A");// here pass the big hex string

            // it will be open in the web browser like this
            document.location.href = 'data:application/pdf;base64,' +data;

     **//to open up in the new window**
    window.open('data:application/pdf;base64,' +data, "_blank", "directories=no, status=no, menubar=no, scrollbars=yes, resizable=no,width=600, height=280,top=200,left=200");
于 2012-06-21T06:29:58.707 回答