1

I am trying to encode a PDF that is remotely on a server (not locally neither selecting files using a javascript/HTML "Browse" button) into BASE64.

I already have checked some examples kindly given by others in StackOverflow such as:

Convert PDF to a Base64-encoded string in Javascript

How to convert file to base64 in JavaScript?

But every time I pass the variable where the remote URL for the PDF is, it shows an error saying:

TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

function funcTransfPDFParaBase64(strCaminhoPDF) {
var reader = new FileReader();

   reader.readAsDataURL(strCaminhoPDF)
   reader.onload = function () {
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
   
   return reader.result;
}

var objTeste = funcTransfPDFParaBase64(strCaminhoPDF);

URL type used in var strCaminhoPDF: https://somesite/fs/file/Download/FileShare/www/Legislation/2015/DL_2015021028.pdf

James Z
  • 12,209
  • 10
  • 24
  • 44
Joao
  • 85
  • 1
  • 9
  • Sounds like an XY problem - why do you need to *encode* (what can be assumed to be an unencoded) PDF from the server? – freedomn-m Jan 12 '22 at 16:30
  • 1
    [MDN FileReader](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) states *To read server-side files, use standard Ajax solutions*. FileReader is for reading local files (eg via an `input`). – freedomn-m Jan 12 '22 at 16:31
  • It is to encode freedomm. Why do I need? Boss told it. lol – Joao Jan 12 '22 at 16:31
  • 1
    [readAsDataURL](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL) can't be used to read from a remote URL, but is made for data in form of a so called [Data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs), e.g `data:application/pdf;base64,JVBERi0xLjQKJe...`, in which the data is already embedded as base64 string. – jps Jan 12 '22 at 16:42
  • Hello jps, yes I know that now, but what I can do? Asynchronous read? – Joao Jan 12 '22 at 16:46

0 Answers0