[英]Javascript: Convert a hexadecimal encoded String to a hexadecimal byte
[英]How to convert Hexadecimal Byte stream in the form of string to actual bytestream in javascript?
我有一个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中完成。 我做了很多搜索,但效果不佳。 我会感激任何帮助。
此致,Riswan
// 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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.