const fs = require('fs'); const path = require('path'); const { execSync } = require('child_process'); const { v4: uuidv4 } = require('uuid'); function convert(base64Data, year, month) { const fileName = uuidv4(); // 一意のファイル名を生成 const tempPdfPath = path.join(__dirname, `${fileName}.pdf`); const tempTxtPath = path.join(__dirname, `${fileName}.txt`); const tempCsvPath = path.join(__dirname, `${fileName}.csv`); try { // base64データをPDFファイルとして保存 fs.writeFileSync(tempPdfPath, Buffer.from(base64Data, 'base64')); // pdftotextでテキスト抽出(-layout -nopgbrk オプションを追加) execSync(`pdftotext -layout -nopgbrk "${tempPdfPath}" "${tempTxtPath}"`); // テキストファイルを1行ずつ読み込み、指定された処理を施す const text = fs.readFileSync(tempTxtPath, 'utf8'); const lines = text.split('\n'); fs.writeFileSync(tempCsvPath, '識別コード,主/副,担当者名,訪問時間,終了時間,対応時間,予防,内容,その他,クライアント,主/副担当者\n'); let subRecord = ''; for (let line of lines) { line = line.replace(/:/gm, ' '); // コロン スペース変換 line = line.replace(/~/gm, ' '); // チルダ スペース変換 line = line.replace("副)", ' 副 '); // 副) スペース変換 line = line.replace(/\(/gm, ''); // カッコ削除 line = line.replace("分)", ''); // 分) 削除 line = line.replace(/^\s+/gm, ''); // 行頭スペース削除 line = line.replace(/\s$/gm, ''); // 行末スペース削除 line = line.replace(/\s+/gm, ' '); // 多重スペース縮小 let record = line.split(/\s/); subRecord = record.length == 1 && record[0]; if (record.length > 10 && record.length < 18) { if (record[1] != '副') { record.splice(1, 0, '主'); } if (record[10] == '予防') { record.splice(12, 0, subRecord); subRecord = ""; } else { record.splice(10, 0, ""); record.splice(12, 0, subRecord); subRecord = ""; } if (record.length == 15) { record.splice(16, 0, ''); record.splice(17, 0, ''); } let output = record.join(','); //カンマ保存 //if (record.length == 16) console.log(record.length + ' ' + record); //インポート用CSVデータ作成 let recordData = `${year}.${month}_${record[2]}${record[3]}_${record[0]},` + `${record[1]},` + `${record[2]} ${record[3]},` + `${year}/${month}/${record[4]} ${record[5]}:${record[6]}:00,` + `${year}/${month}/${record[4]} ${record[7]}:${record[8]}:00,` + `${record[9]},` + `${record[10]},` + `${record[11]},` + `${record[12]},` + `${record[13]} ${record[14]},`; if (record[15] != '') { recordData += `${record[15]} ${record[16]}`; } fs.appendFileSync(tempCsvPath, recordData + '\n'); } } // CSVデータを返す return fs.readFileSync(tempCsvPath, 'utf8'); } finally { // 一時ファイル削除 [tempPdfPath, tempTxtPath, tempCsvPath].forEach(file => { if (fs.existsSync(file)) fs.unlinkSync(file); }); } }