Untitled

mail@pastecode.io avatar
unknown
plain_text
25 days ago
5.1 kB
0
Indexable
Never
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSON Converter</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            background-color: #f0f0f0;
        }
        form {
            display: flex;
            flex-direction: column;
            background: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        input, select, button {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <h1>JSON Converter</h1>
    <form id="convert-form">
        <label for="json-input">JSON Input:</label>
        <textarea id="json-input" rows="10" cols="50"></textarea>
        <label for="format">Select Format:</label>
        <select id="format">
            <option value="csv">CSV</option>
            <option value="pdf">PDF</option>
            <option value="excel">Excel</option>
        </select>
        <button type="button" onclick="convert()">Convert</button>
    </form>
    <script>
        function convert() {
            const jsonInput = document.getElementById('json-input').value;
            const format = document.getElementById('format').value;

            const formData = new FormData();
            formData.append('data', jsonInput);
            formData.append('format', format);

            fetch('/convert', {
                method: 'POST',
                body: formData,
            })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => { throw new Error(text) });
                }
                return response.blob();
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', `data.${format}`);
                document.body.appendChild(link);
                link.click();
                link.parentNode.removeChild(link);
            })
            .catch(error => console.error('Error:', error));
        }
    </script>
</body>
</html>






const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const PDFDocument = require('pdfkit');
const ExcelJS = require('exceljs');
const fs = require('fs');
const path = require('path');
const app = express();

app.use(bodyParser.json());
app.use(express.static('public'));

const upload = multer({ storage: multer.memoryStorage() });

app.post('/convert', upload.none(), async (req, res) => {
    const data = req.body.data;
    const format = req.body.format;

    if (!data || !format) {
        return res.status(400).send('Invalid input');
    }

    let jsonData;
    try {
        jsonData = JSON.parse(data);
    } catch (error) {
        return res.status(400).send('Invalid JSON');
    }

    if (format === 'csv') {
        convertToCSV(jsonData, res);
    } else if (format === 'pdf') {
        convertToPDF(jsonData, res);
    } else if (format === 'excel') {
        await convertToExcel(jsonData, res);
    } else {
        res.status(400).send('Invalid format type');
    }
});

function convertToCSV(data, res) {
    const fields = Object.keys(data[0]);
    const csv = data.map(row => fields.map(field => JSON.stringify(row[field], replacer)).join(','));
    csv.unshift(fields.join(',')); // add header column
    res.header('Content-Type', 'text/csv');
    res.attachment('data.csv');
    res.send(csv.join('\r\n'));

    function replacer(key, value) {
        return value === null ? '' : value;
    }
}

function convertToPDF(data, res) {
    const doc = new PDFDocument();
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=data.pdf');
    doc.pipe(res);

    const fields = Object.keys(data[0]);
    fields.forEach(field => {
        doc.text(field, { continued: true }).text('\t');
    });
    doc.text('\n');

    data.forEach(row => {
        fields.forEach(field => {
            doc.text(row[field], { continued: true }).text('\t');
        });
        doc.text('\n');
    });

    doc.end();
}

async function convertToExcel(data, res) {
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Sheet1');

    worksheet.columns = Object.keys(data[0]).map(key => ({ header: key, key }));

    data.forEach(row => {
        worksheet.addRow(row);
    });

    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', 'attachment; filename=data.xlsx');

    await workbook.xlsx.write(res);
    res.end();
}

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});
Leave a Comment