Markdown to PDF Converter with Node.js and Express

Markdown to PDF Converter with Node.js and Express

ยท

2 min read

To create a Markdown to PDF Converter with Node.js and Express, you can use a package called markdown-pdf along with Express for handling the web server. Here is a step-by-step guide:

Step 1: Set Up Your Project

  1. Create a new project folder:

     mkdir markdown-to-pdf-converter
     cd markdown-to-pdf-converter
    
  2. Initialize a new Node.js project:

     npm init -y
    
  3. Install necessary packages:

     npm install express markdown-pdf
    

Step 2: Create the Express Server

Create an index.js file to set up your Express server:

// index.js
const express = require('express');
const bodyParser = require('body-parser');
const markdownpdf = require('markdown-pdf');

const app = express();
const PORT = process.env.PORT || 3000;

app.use(bodyParser.text()); // Parse text/plain content type

app.post('/convert', (req, res) => {
  const markdownContent = req.body;

  if (!markdownContent) {
    return res.status(400).send('No Markdown content provided');
  }

  // Convert Markdown to PDF
  const pdfStream = markdownpdf().from.string(markdownContent).to.stream();

  // Set response headers for PDF
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', 'attachment; filename=converted.pdf');

  // Pipe the PDF stream to the response
  pdfStream.pipe(res);
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 3: Create a Simple Frontend (Optional)

Create a simple HTML file for the frontend where users can input Markdown content:

<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Markdown to PDF Converter</title>
</head>
<body>
  <h1>Markdown to PDF Converter</h1>
  <textarea id="markdownInput" rows="10" cols="80"></textarea>
  <button onclick="convertToPDF()">Convert to PDF</button>

  <script>
    async function convertToPDF() {
      const markdownContent = document.getElementById('markdownInput').value;

      if (!markdownContent) {
        alert('Please provide Markdown content');
        return;
      }

      const response = await fetch('/convert', {
        method: 'POST',
        headers: {
          'Content-Type': 'text/plain',
        },
        body: markdownContent,
      });

      if (response.ok) {
        // Download the converted PDF
        const blob = await response.blob();
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = 'converted.pdf';
        link.click();
      } else {
        alert('Failed to convert to PDF');
      }
    }
  </script>
</body>
</html>

Step 4: Update Express Server to Serve Static Files

Update the index.js file to serve static files from the public folder:

// index.js
// ... (previous code)

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

// ... (remaining code)

Step 5: Test Your Markdown to PDF Converter

  1. Start your Express server:

     node index.js
    
  2. Open your browser and visit http://localhost:3000.

  3. Enter Markdown content in the textarea and click the "Convert to PDF" button.

  4. Download and inspect the converted PDF file.

Congratulations! You've successfully created a Markdown to PDF Converter with Node.js, Express, and markdown-pdf. Customize and expand this implementation based on your specific requirements.

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย