Html DOM to Array Buffer to make BLOB for pdf? - javascript

I want to show my HTML DOM as pdf in new tab using BLOB. We can achieve this by calling a API which will return a blob but I want to do this without the involvement of any server side API. I am facing problems in converting my html string to ARRAY BUFFER. Here is the code on stackblitz you can test this and please let me know how to solve this. Thanks
generate pdf from html dom

Consider using TextEncoder, which can easily encode/decode Strings and ArrayBuffers:
const encoder = new TextEncoder(),
decoder = new TextDecoder(),
text = 'Hello',
textEncoded = encoder.encode(text),
textDecoded = decoder.decode(textEncoded);
console.log({ text, textDecoded, textEncoded });

Related

How to view blob data directly using html

How do you view a blob data that is from a sql database file (.db .db3 and others) and view it on web browser by only using a single html file? The blob data are probably meant to be seen as an image file (jpg, png and others)
Let's say I have a blob data like this:
du�� C�BVwv�q8q7k�1�H�asfdasdfasdf�#s;47sk"as��'7hib-�3$asdffdsfa�a�����U�����P������
And I want to put that single blob data directly (without calling the database file, just using the value of the blob itself) inside a html file so I can directly open it from my browser without installing other software or setting up a local server inside my computer.
I'm sorry if I explain this weirdly, I rarely code, I honestly don't know anything about sql or that server thingamajig, I just want to view the blob file.
You could use Blob. Here I construct a blob and then turn it back into a string that I insert in the document.body.
var array = ['<p>Hello World!</p>'];
var blob = new Blob(array, {type : 'text/html'});
const reader = new FileReader();
reader.addEventListener('loadend', e => {
document.body.innerHTML += e.target.result;
});
reader.readAsText(blob);
And I guess that the Filereader can also read a file if needed.

NodeJS Converting text buffer to viewable HTML Page

I am receiving data reading from an S3 bucket, which will contain .html files. they are being received by Node like so:
{"type":"Buffer","data":[60,104,116,109,108,32,120,109,108,110,115,58,118,61,34,117,114 ....]}
Is there any way you can take this buffer and use it somewhere to insert directly into like an iFrame src? Or what would be the best way to go about taking this buffer and being able to show it as an HTML page?
Was also thinking of taking the buffer and writing the file with fs.writeFile(...) and using the local path as the src.
Any suggestions / advice would be appreciated thank you in advance.
That would work as well
const d = {"type":"Buffer","data":[60,104,116,109,108,32,120,109,108,110,115,58,118,61,34,117,114]}
const r = Buffer.from(d.data).toString()
console.log(r) // <html xmlns:v="ur
You can convert the ArrayBuffer to a String easily. Given your partial Buffer, it would look like this:
const dataFromS3 = {"type":"Buffer","data":[60,104,116,109,108,32,120,109,108,110,115,58,118,61,34,117,114]};
const output = String.fromCharCode.apply(null, dataFromS3.data);
console.log(output);

How can I convert a string of pdf code into a blob?

I briefly summarize my problem:
I'm calling an API that returns a pdf like
"% PDF-1.4%%1 0 obj
<<
/ Type / Catalog/ PageLayout / OneColumn/
Pages 2 0 R/ PageMode / UseNone
......... "
currently, I receive it in string format to be able to make changes and so far so good, but after making changes I would like to convert the string to blob to download the pdf. In doing this I am having problems, the text string converted to blob does not generate the correct pdf, or rather the pdf once opened is white, when in reality it should have data.
The code I'm using now is the following:
response.text().then((content) => {
//...TODO: Modify pdf
var blob = new Blob([content], { type: "application/pdf" });
saveAs(blob, "invoice.pdf");
}).catch(error => {
console.log(error);
});
The pdf is downloaded but if I open it it is empty.
I would like to be able to modify the pdf string and convert it back into a blob to be able to download it.
Does anyone have an idea how I could do it?
A PDF consists of a set of objects in a non-trivial fashion. If you are receiving it as a string and are using standard string manipulation functions on it, e.g. find and replace you are most likely going to corrupt it. You would have to edit in accord with the standards laid out in the PDF specification and not violate the syntax. This is a very fragile approach, you need to use a PDF library instead to edit your PDF content.

Mechanisms for hashing a file in JavaScript

I am relatively new to JavaScript and I want to get the hash of a file, and would like to better understand the mechanism and code behind the process.
So, what I need: An MD5 or SHA-256 hash of an uploaded file to my website.
My understanding of how this works: A file is uploaded via an HTML input tag of type 'file', after which it is converted to a binary string, which is consequently hashed.
What I have so far: I have managed to get the hash of an input of type 'text', and also, somehow, the hash of an uploaded file, although the hash did not match with websites I looked at online, so I'm guessing it hashed some other details of the file, instead of the binary string.
Question 1: Am I correct in my understanding of how a file is hashed? Meaning, is it the binary string that gets hashed?
Question 2: What should my code look like to upload a file, hash it, and display the output?
Thank you in advance.
Basically yes, that's how it works.
But, to generate such hash, you don't need to do the conversion to string yourself. Instead, let the SubtleCrypto API handle it itself, and just pass an ArrayBuffer of your file.
async function getHash(blob, algo = "SHA-256") {
// convert your Blob to an ArrayBuffer
// could also use a FileRedaer for this for browsers that don't support Response API
const buf = await new Response(blob).arrayBuffer();
const hash = await crypto.subtle.digest(algo, buf);
let result = '';
const view = new DataView(hash);
for (let i = 0; i < hash.byteLength; i += 4) {
result += view.getUint32(i).toString(16).padStart(2, '0');
}
return result;
}
inp.onchange = e => {
getHash(inp.files[0]).then(console.log);
};
<input id="inp" type="file">

How can I convert an HTML string to PNG byte array in Node.JS?

I am relatively new to Node.JS and have been researching how to convert HTML in a string (which is an HTML email template) to a PNG image in a byte array. Reviewing through multiple npm packages, all reference how to convert an HTML file to a PNG file or if using an HTML string, they seek to extract a div, svg, or another element from within the HTML. Does anyone have an example for this type of situation?
try this one: html-convert
Render a webpage and get the image as a stream.
npm install html-convert
example:
var htmlConvert = require('html-convert');
var fs = require('fs');
var convert = htmlConvert(); // convert a website url
convert('http://example.com/my-site').pipe(fs.createWriteStream('out.png')); // or as a transform stream
fs.createReadStream('some-html-file.html')
.pipe(convert())
.pipe(fs.createWriteStream('out.png'))

Categories