I need a help about my code. I get a field BytesBoleto in a Base64 encoded pdf. I need to filter them from a json and save the pdf files on user desktop. How can I do that? What´s wrong with my code?
I got the error; “The “data” argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of File”
Here is my code:
// Função para decodificar Base64 e criar arquivos PDF
function gerarPDFsDeJson(jsonData) {
// Verifica se jsonData é um objeto
if (typeof jsonData !== 'object' || jsonData === null) {
throw new Error("Entrada inválida: deve ser um objeto JSON.");
}
// Array para armazenar os arquivos PDF
const pdfFiles = [];
// Função recursiva para percorrer o JSON e encontrar os campos "BytesBoleto"
function procurarBytesBoleto(obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (key === 'BytesBoleto' && typeof obj[key] === 'string') {
// Decodifica a string Base64
const byteCharacters = atob(obj[key]);
const byteNumbers = new Uint8Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const blob = new Blob([byteNumbers], { type: 'application/pdf' });
const pdfFile = new File([blob], `${key}.pdf`, { type: 'application/pdf' });
pdfFiles.push(pdfFile);
} else if (typeof obj[key] === 'object') {
procurarBytesBoleto(obj[key]); // Chama a função recursivamente
}
}
}
}
procurarBytesBoleto(jsonData);
return pdfFiles;
}
// Function to save PDF files to desktop
function savePDFsToDesktop(buffers, keys) {
const desktopPath = path.join(require('os').homedir(), 'Desktop'); // Get user's desktop path
buffers.forEach((buffer, index) => {
const filePath = path.join(desktopPath, `${keys[index]}.pdf`);
fs.writeFile(filePath, buffer, (err) => {
if (err) {
console.error(`Error saving ${keys[index]}.pdf:`, err);
} else {
console.log(`Successfully saved ${keys[index]}.pdf to ${desktopPath}`);
}
});
});
}
// Function to save files
const fs = require('fs');
const path = require('path');
// Assuming you have an array of Buffer data and keys for the PDF files
const keys = ['file1', 'file2']; // Corresponding keys for file names
// Exemplo de uso
const jsonExample = {
documentos: [
{ BytesBoleto: "JVBERi0xLjQKJeLjz9MKNCAwIG9iaiA8PC9Qcm9jU2V0IDggMCBSIC9FbmNvZGluZyA8PC9MZW5ndGggNjY1ID4+PgplbmRvYmoK" },
{ BytesBoleto: "JVBERi0xLjQKJeLjz9MKNCAwIG9iaiA8PC9Qcm9jU2V0IDggMCBSIC9FbmNvZGluZyA8PC9MZW5ndGggNjY1ID4+PgplbmRvYmoK" },
]
};
const pdfFilesArray = gerarPDFsDeJson(jsonExample);
console.log(pdfFilesArray); // Aqui você terá um array de arquivos PDF
// Call the function to save the PDFs
savePDFsToDesktop(pdfFilesArray, keys);
Thanks for the help