How to Convert Pdf to Base64 and Encode/Decode

How to Convert Pdf to base64 and Encode / Decode

You can decode base64 encoded String and pass that byte[] to FileOutputStream write method to fix this issue.

        String filePath = "C:\\Users\\xyz\\Desktop\\";
String originalFileName = "96172560100_copy2.pdf";
String newFileName = "test.pdf";

byte[] input_file = Files.readAllBytes(Paths.get(filePath+originalFileName));

byte[] encodedBytes = Base64.getEncoder().encode(input_file);
String encodedString = new String(encodedBytes);
byte[] decodedBytes = Base64.getDecoder().decode(encodedString.getBytes());

FileOutputStream fos = new FileOutputStream(filePath+newFileName);
fos.write(decodedBytes);
fos.flush();
fos.close();

PDF file content to Base 64 and vice versa in Java

Why are you doing:

String pdfStr = new String(pdfRawData);

instead of passing pdfRawData to the encoder?

Doing so lead to lots of encoding issue, as you don't specify the encoding of the byte array to use to build the string (it will use platform default). And this is clearly redondant (byte array -> string -> byte array)

creating a pdf and converting it to base64

I'd never use Emailjs but maybe that's your solution for your pdf file

const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});

async function Main() {
const file = document.querySelector('#myfile').files[0];
const result = await toBase64(file).catch(e => Error(e));
if(result instanceof Error) {
console.log('Error: ', result.message);
return;
}


Main();

PHP base64 encode a pdf file

base64_encode takes a string input. So all you're doing is encoding the path. You should grab the contents of the file

$b64Doc = chunk_split(base64_encode(file_get_contents($this->pdfdoc)));

How to base64 encode a raw PDF content (bytes) in JAVASCRIPT?

If you are storing contents as Blob, use the FileReader object to convert it to data URI, then remove its prefix:

var reader = new FileReader();
reader.onload = function () {
var b64 = reader.result.replace(/^data:.+;base64,/, '');
console.log(b64);
};
reader.readAsDataURL(your_blob);

Another way, if you are storing it as ArrayBuffer:

// Create a Uint8Array from ArrayBuffer
var codes = new Uint8Array(your_buffer);

// Get binary string from UTF-16 code units
var bin = String.fromCharCode.apply(null, codes);

// Convert binary to Base64
var b64 = btoa(bin);
console.log(b64);


Related Topics



Leave a reply



Submit