I want to convert base64 string of a Word doc to a base64 string of PDF in JavaScript/Angular 9 - pdf-generation

I am using the docx library to generate a Word document (.docx) on the client side (Angular 9). I also want to be able to save the file as a pdf. I can get a base64 string/uint8array/blob, but I believe this is different for different types of documents. Because when I save the file as a pdf it is corrupted. Is there a way to convert the base64 string of a word doc to base64 string of pdf in JavaScript?
Packer.toBase64String(doc).then((string) => {
// Convert this bas64 encoded word string to base64 encoded pdf string
});
Alternatively, if we can convert the blob too, that is fine.
Packer.toBlob(doc).then((blob) => {
//convert word blob to pdf blob
saveAs(blob, 'example.pdf');
});

The short answer is no (not directly)
As you say they are totally different textual expansions of different types of compressed (encoded) "binary" sources.
Base64 is used to transfer a binary file without corruption due to Text Transfer (the TT in HTTPS) so a file can be reproduced from binary to text then transferred (we call that download, hence HTML PDF etc. are always downloaded from server to client) and converted back into binary. Similar for email attachments.
So the long winded answer to the question is
Use the OS base64 tool or AtoB.js to convert base64.txt to compressed binary.DocX or .PDF as required
Then use use a binary converter library to decompress and re-compress as either doc2pdf or pdf2doc
Then use base64 to expand it back again to transmittable text so that it can be re-compressed at the receiver back into binary.

Related

How to decode base64 & hexadecimal response from query

The query comes as
"returnData": [
"zWCLtKpUXZbkWNM9deAVPizTxXASOjX63ubdUHDN+vw=",
"zWCLtKpUXZbkWNM9deAVPizTxXASOjX63ubdUHDN+vw="
],
How can I decode that string? I can see it is decodable base64 first, but I get a very weird string after. Can someone show me the steps to follow to receive the decoded final string?
Base64 encodes binary data, which means if you send data that is not a string you won't be able to retrieve a string back. So to properly parse the return data you will need to know what data types were actually returned.
It might also be helpful to use a base64 to hex decoder first, so you get the hex representation of your data.
To give you more concrete recommendations we would need to know what data you expected, preferably showing the whole endpoint definition as well as any custom structs that might be involved.

Regarding conversion of image-to-base64 string in TouchDevelop

I am getting an image (encoded in base64 string format) from a server. This base64-encoded string has to be converted back to image. I am doing in two steps:
Convert the base64 encoded string into a buffer - Using bits -> string to buffer(string,"base64")
Write the buffer into a picture (of same dimensions) - Using Picture -> write buffer(buffer) and then I'm displaying the picture.
The base64 string from the server (whole string):
iVBORw0KGgoAAAANSUhEUgAAAJEAAAAeCAYAAAAsPvwuAAAAmUlEQVR42u3SQQoAIQgAwL7h/x+6sQsLHcqCPI7QITGNmvYsIiK+leX+/ZjPcifnsnvs5pzW3PaunLGrm/W6eZPqv3yjQQQRRBBBBBFEEEEEEUQQQQQRRBBBBBFEEEEEEUQQQQQRRBBBBBFEEEEEEUQQQQQRRBBBBBFEEEEEEUQQQQQRRBBBBBFEEEEEEUQQQQQRRBBBVIuoAwQlLkAhgPjNAAAAAElFTkSuQmCC
The problem is: I am not getting the desired image when I display it on the wall. It just shows a very small image.
So I tried finding what string TouchDevelop expected in bits -> string to buffer(string,"base64") method.
I obtained the original image from online converter (http://www.motobit.com/util/base64-decoder-encoder.asp) supplying the same string as obtained from the server. This image was correct.
Then I did the reverse process of what I described above – Converting an image into base64 string. This, I did by using Picture to buffer(Picture) and then buffer to string(“base64“) and displayed the base64 string as generated by TouchDevelop for the same image.
The base64 string I got from TouchDevelop (just a small part of actual string - Actual string size-23,300 chars):
////////////////////////////////GRkZ/xkZGf////////////////8ZGRn/GRkZ////////////GRkZ/xkZGf8ZGRn/GRkZ//////8ZGRn/GRkZ/xkZGf8ZGRn//////xkZGf8ZGRn///////////8ZGRn/GRkZ/xkZGf8ZGRn//////xkZGf8ZGRn//////////////////////xkZGf8ZGRn//////xkZGf8ZGRn//////xkZGf8ZGRn/GRkZ/xkZGf///////////xkZGf8ZGRn//////xkZGf8ZGRn/GRkZ/xkZGf//////////////////////GRkZ/xkZGf//////GRkZ/xkZGf//////GRkZ/xkZGf8ZGRn/GRkZ////////////GRkZ/xkZGf8ZGRn/GRkZ//////8ZGRn/GRkZ/xkZGf8ZGRn//////////////////////xkZGf8ZGRn//////xkZGf8ZGRn//////xkZGf8ZGRn///////////8ZGRn/GRkZ//////8ZGRn/GRkZ//////////////////////8ZGRn/GRkZ/xkZGf8ZGRn//////xkZGf8ZGRn//////xkZGf8ZGRn/GRkZ/xkZGf///////////xkZGf8ZGRn////////////////……
As you might have noticed, the base64 string from the server and the base64 string what TouchDevelop expects to show the correct image have a huge difference. And this is resulting into displaying of an incorrect image. I am stuck in this problem for a few days. Is there a bug? If not, can anyone help me with this problem?

How do I write png hex values stored in a string to a png file in Ruby?

I have a png image hex values stored in a string but I want to write this to a new png file to be viewed. I currently using the Ruby code below (with a small png example) but the hex values are slightly off when I check the output in the new png file. Where am I going wrong?
png_hex = "89504e470d0a1a0a0000000d494844520000000d0000000d08030000004535144e0000000774494d4507d7041517171c5943ea76000000097048597300000b1100000b11017f645f910000000467414d410000b18f0bfc610500000015504c544500000086c1e01544706ba4da4a85c6386c9f427ab6583bfce90000000174524e530040e6d866000000434944415478da558d41120030040395c8ff9f5cd421dd0b6b02b3e198c24f1d22c72996bed1683c89ae3d2f4856ed6570795b317dec0da45aba04ad2e761cfb7a4228bb5cb30147915c409a0000000049454e44ae426082"
File.open("temp.png", "w"){|fh|
fh.print png_hex.scan(/.{2}/).map{|u| u.to_i(16)}.pack("C*")
}
Use "wb" instead of "w" to open the file in binary mode:
"b" Binary file mode
Suppresses EOL <-> CRLF conversion on Windows. And
sets external encoding to ASCII-8BIT unless explicitly
specified.
(source)
By the way, you can call
IO#putc to directly write an 8-bit integer to the IO stream without having to create an array and packing integers:
File.open("temp.png", "wb"){|fh|
png_hex.scan(/.{2}/) { |e| fh.putc(e.hex) }
}

Convert base64 byte array to an image

I have a form bean with attributes id, desc and imageByteArray. Struts action gets executed and it redirects to a JSP where i want to access these bean attributes like id, desc and convert the imageByteArray and display it as an image. I tried this post, but that's not working for me.
I encode the bytearray using Base64 - where this.bean.imageByteArray refers to the form bean
this.bean.setImageByteArray(new org.apache.commons.codec.binary.Base64().encode(imageInByteArr));
I tried this, but not working
<img src="data:image/jpg;base64,<c:out value='${bean.imageByteArray}'/>" />
Byte array (byte[] imageByteArray) refers a base64 encoded JPG image and I'm getting the following img tag as output and obviously nothing gets displayed,
<img src="data:image/jpg;base64,[B#2e200e">
Any idea how to convert base64 byte array and display as an image in JSP?
What you get is just the toString output of an array. You need however the byte array converted to a String.
You should create a method in bean
public String getByteArrayString()
{
return new String(this.imageByteArray);
}
and reference this in your JSP.
While technically you should define which encoding to use for an array of base64 bytes this is not necessary as all characters are in the standard 7bit ASCII range.
DoubleMalt's answer (accepted at the time of writing) is unfortunate, because it's sort of using two wrongs to make a right. It doesn't help that Apache Commons Codec makes it so easy to do the wrong thing :(
Base64 is fundamentally an encoding from binary data to text - as such, it should almost always be used to convert a byte[] to a String. Your issue is that you're converting a byte[] to another byte[] - but you later want to use that data as a string. It would be better to convert once, in the right way.
Now you can choose exactly when you convert to base64 (and a string). You could do it early, in your Java code, in which case I'd use:
// Obviously you'd need to introduce a new method for this, replacing
// setImageByteArray
this.bean.setImageBase64(new Base64().encodeToString(imageInByteArr));
<img src="data:image/jpg;base64,<c:out value='${bean.imageBase64}'/>" />
Alternatively, you could keep just the binary data in your bean, and the perform the encoding in the JSP. It's been a long time since I've written any JSPs, so I'm not going to try to write the code for that here.
But basically, you need to decide whether your bean should keep the original binary data as a byte[], or the base64-encoded data as a String. Anything else is misleading, IMO.

How can I do a Get on an InputStream?

One annoying thing of encoded packages is that they have to be in a separate file. If we want to distribute a simple self contained app (encoded), we need to supply two files: the app "interface", and the app package.
If I place all the content of the encoded file inside a string, and transform that string into an InputStream, I'm halfway to view that package content as a file.
But Get, that to my knowledge is the only operation (also used by Needs) that has the decoding function, doesn't work on Streams. It only works on real files.
Can someone figure out a way to Get a Stream?
Waiting for Mathematica to arrive on my iPhone so couldn't test anything, but why don't you write the string to a temporary file and Get that?
Update
Here's how to do it:
encoded = ToFileName[$TemporaryDirectory, "encoded"];
Export[encoded, "code string", "Text"]; (*export encrypted code to temp file *)
It's important to copy the contents of the code string from the ASCII file containing the encoded code using an ASCII editor and paste it between existing empty quotes (""). Mathematica will then do automatic escaping of backslashes and quotes that may be in the code. This file has been made earlier using Encode. Can't do it here in the sample code as SO's Markdown messes with the string.
Get[encoded] (* get encrypted code and decode *)
DeleteFile[encoded] (* Remove temp file *)
Final Answer
Get doesn't appear to be necessary for decoding. ImportString does work as well:
ImportString["code string", "NB"]
As above, paste your encoded tekst from an ASCII editor straight between the "" and let MMA do the escaping.
I don't know of a way to Get a Stream, but you could store the encoded data in your single package, write it out to a temp file, then read the temp file back in with Get.
Just to keep things up to date:
Get works with streams since V9.0.

Resources