Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save pdf in proper encoding via nodejs

So I'm trying to download a pdf file from a website with my script but the problem is that the file gets broken in the process and I'm pretty sure it's because of wrong encoding being used.

I'm using request lib for downloading the file and I've set the Content-type to application-pdf

My code is pretty simple:4

var fs = require('fs');
var request = require("request");


request({uri: 'xxxxxxxxxxxxxx.pdf', headers: { 'Content-type' : 'applcation/pdf' }} , function (error, response, body) {
  if (!error && response.statusCode == 200) {
    fs.writeFileSync("10111.pdf", body);
  }
})

Where do I need to specify the encoding used for this to work?

I tried opening the pdf that I get by normal saving and SublimeText3 encodinghelper says it's in Windows-something while the one I downloaded is in utf8.

I've gone through the nodejs buffer and fs files and they do not supprt encodings like windows-asd, only the general ones like 'utf8' and 'binary'.

Should I maybe use a different method for obtaining the file?

like image 457
ditoslav Avatar asked Jun 25 '15 02:06

ditoslav


People also ask

How do I save node JS as a PDF?

To save a PDF document to a file on disk, invoke its Save() method: async function main() { doc.

What is the encoding for PDF files?

PDF character encoding determines the character set that is used to create PDF files. You can choose to use Windows1252 encoding, the standard Microsoft Windows operating system single-byte encoding for Latin text in Western writing systems, or unicode (UTF-16) encoding.

What is encoding in node JS?

The setEncoding function in Node. js alters the encoding of character data stored inside a readable stream. It comes as part of the stream module. By changing character encodings, programmers can use the setEncoding method to interpret the same piece of data in multiple ways.

How do I save a file in node JS?

writeFile("/tmp/test", message, function (err) { if (err) { return console. log(err); } console. log("The file was saved!"); }); }); Hope this works for you.


1 Answers

I know its very late but i seen your question today so i am answering it so that other can get help from this. You can add the encoding when you are trying to write the file i.e-:

fs.writeFileSync("10111.pdf", body,'binary');

As i set encoding format as binary here you can use which is right encoding format according to your requirenment if you are trying to download a pdf that you can set encoding as null.

Hope this would help

like image 161
Parveen yadav Avatar answered Sep 29 '22 07:09

Parveen yadav