ken_nogi/NodeJS/ExcelToPDF/sendExcelFile.js
Kenichiro NOGI 51a95c5e21 NodeJS
2025-07-10 10:12:37 +09:00

92 lines
3.4 KiB
JavaScript

//const fetch = require('node-fetch');
// 送信先サーバーのURLとAPIキー
const SERVER_URL = 'https://neo999.next-hd.net:30309/pdfConvert'; // サーバーのURLに合わせて変更
const API_KEY = 'pgqhLFWbDFu4Byz#4afNYX2F6Fa1&$KPjved$8%sUdTQV52caip#EpIKxYUkdd4S'; // サーバーと同じAPIキー
// base64とfileNameを引数で受け取り、変換後のPDFを自動ダウンロード
async function sendExcelAndSavePdf(base64, fileName) {
try {
const response = await fetch(SERVER_URL, {
method: 'POST',
body: JSON.stringify({ base64, fileName }),
headers: {
'Content-Type': 'application/json',
'x-api-key': API_KEY
}
// agent: new https.Agent({ rejectUnauthorized: false }) // ブラウザでは不要
});
if (!response.ok) {
throw new Error(`サーバーエラー: ${response.status} ${response.statusText}`);
}
// PDFバイナリを取得
const pdfBlob = await response.blob();
// 自動ダウンロード処理
const url = window.URL.createObjectURL(pdfBlob);
const a = document.createElement('a');
a.href = url;
if (!(fileName.endsWith('.xlsx') || fileName.endsWith('.docx') || fileName.endsWith('.pptx'))) {
alert('対応していないファイル形式です。');
return;
} else {
fileName = fileName.replace(/\.(xlsx|docx|pptx)$/, '.pdf');
}
a.download = fileName;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
console.log('PDFのダウンロードを開始しました');
} catch (err) {
console.error('変換エラー:', err.message);
}
}
// Excelファイルをbase64に変換して関数を呼び出す例
// const excelBuffer = fs.readFileSync(excelFilePath);
// const base64 = excelBuffer.toString('base64');
// const fileName = path.basename(excelFilePath);
// sendExcelAndSavePdf(base64, fileName);
//Guidを指定してfetchでファイルのbase64データとファイル名を取得する関数
async function fetchFileBase64(guid) {
const apiKey = '6504c8a807677a3a576e10327f3c19876c55736ee45d4a845796b9e7f5e087bfd4bd0d8184863da8cf1733ca635111432ab334aea59102b06a96ee6d2c05190d';
const url = 'https://' + location.hostname + '/pleasanter/api/binaries/' + guid + '/get';
const jsonBody = {
'ApiVersion': 1.1,
'ApiKey': apiKey,
}
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(jsonBody)
});
const resData = await res.json();
console.log(resData);
const base64 = resData.Response.Base64;
const fileName = resData.Response.FileName;
const ext = resData.Response.Extension;
if (!(ext === '.xlsx' || ext === '.docx' || ext === '.pptx')) {
throw new Error('指定されたファイルはExcel、Word、またはPowerPointファイルではありません。');
} else {
return { base64, fileName };
}
}
function converToPDF() {
let files = JSON.parse($('#Results_AttachmentsA').val());
for (let file of files) {
fetchFileBase64(file.Guid)
.then(({ base64, fileName }) => sendExcelAndSavePdf(base64, fileName))
.catch(err => console.error('PDF変換API送信エラー:', err));
}
}