const axios = require('axios');
const fs = require('fs');
const downloadPdf = async () => {
// Base API URL
const baseApiUrl = 'http://10.1.91.80:2018/WebApi';
const pdfUrl = `${baseApiUrl}/Vendas/Docs/PrintDocumentToPDF/FA/2024/1489/000/1/FAHB/true/FATURA/0`;
try {
// Step 1: Get the token
const tokenResponse = await axios.post(`${baseApiUrl}/token`, {
username: 'primavera',
password: 'abcd#',
company: '',
instance: 'Default',
line: 'executive',
grant_type: 'password'
});
if (tokenResponse.status !== 200) {
console.error('Failed to retrieve token:', tokenResponse.status);
return;
}
const token = tokenResponse.data.access_token;
if (!token || token.length === 0) {
console.error('Token not found.');
return;
}
// Step 2: Request the PDF using the token
const pdfResponse = await axios.get(pdfUrl, {
headers: {
Authorization: `Bearer ${token}`,
},
responseType: 'arraybuffer', // Ensure we receive binary data
});
if (pdfResponse.status === 200) {
// Save the PDF content to a file
fs.writeFileSync('documento.pdf', pdfResponse.data);
console.log('PDF downloaded successfully as "documento.pdf"');
} else {
console.error('Failed to download PDF:', pdfResponse.status);
}
} catch (error) {
console.error('Error:', error.message);
}
};
// Call the function
downloadPdf();