Build a PDF to Audio Mp3 Converter Web App in Node.js and Express Using GTTS Library Full Tutorial For Beginners

Build a PDF to Audio Mp3 Converter Web App in Node.js and Express Using GTTS Library Full Tutorial For Beginners

 

 

 

Welcome folks in this blog post we will be building a web app in which we will be converting pdf documents to audio mp3 using node.js and express. And for this we will be using the library called as gtts for converting text to audio.

 

Live Demo

 

You can see the live demo of app here

 

 

Get Started

 

 

In order to get started you need to install the following dependencies

 

npm i express

 

npm i multer

 

npm i ejs

 

npm i gtts

 

npm i pdf-text-extract

 

npm i nodemon

 

After installing all the dependencies make a index.js file and copy paste the following code

 

 

const express = require("express")

const multer = require("multer")

const path = require("path")

const fs = require("fs")

var dir = "public";
var subDirectory = "public/uploads";

if (!fs.existsSync(dir)) {
  fs.mkdirSync(dir);

  fs.mkdirSync(subDirectory);
}


const gtts = require("gtts")

const extract = require("pdf-text-extract")

const bodyparser = require("body-parser")

const app = express()

app.set("view engine","ejs")
app.use(bodyparser.json())

app.use(bodyparser.urlencoded({extended:false}))
const PORT = 5000

const pdfFilter = function (req, file, callback) {
  var ext = path.extname(file.originalname);
  if (ext !== ".pdf") {
    return callback("This Extension is not supported");
  }
  callback(null, true);
};

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads");
  },
  filename: function (req, file, cb) {
    cb(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});

app.get("/pdftoaudio", (req, res) => {
  res.render("pdftoaudio", {
    title:
      "FREE PDF to Audio Mp3 Online Tool | Convert PDF Text to Audio Mp3 Online - FreeMediaTools.com",
  });
});

var pdftoaudioupload = multer({
  storage: storage,
  fileFilter: pdfFilter,
}).single("file");

app.post("/uploadpdftoaudio", (req, res) => {
  pdftoaudioupload(req, res, function (err) {
    if (err) {
      return res.end("Error uploading file.");
    }
    res.json({
      path: req.file.path,
    });
  });
});

app.post("/pdftoaudio", (req, res) => {
  outputfile = Date.now() + "output.txt"
  extract(req.body.path, { splitPages: false }, function (err, text) {
    if (err) {
      console.dir(err);
      return;
    }
    console.log(text);
    fs.writeFileSync(outputfile, text);

    console.log(fs.readFileSync(outputfile,'utf-8'))

    var gttsVoice = new gtts(fs.readFileSync(outputfile,'utf-8'), req.body.language);

    outputFilePath = Date.now() + "output.mp3";


    gttsVoice.save(outputFilePath, function (err, result) {
      if (err) {
        fs.unlinkSync(outputFilePath);
        res.send("An error takes place in generating the audio");
      }
      res.json({
        path: outputFilePath,
      });
    });
  });
});

app.get("/download", (req, res) => {
  var pathoutput = req.query.path;
  console.log(pathoutput);
  var fullpath = path.join(__dirname, pathoutput);
  res.download(fullpath, (err) => {
    if (err) {
      fs.unlinkSync(fullpath);
      res.send(err);
    }
    fs.unlinkSync(fullpath);
  });
});


app.listen(PORT, () => {
  console.log(`App is listening on Port ${PORT}`);
});

 

See also  Node.js Alipay Payment Gateway Integration in Website Using alipay-nodejs Library in Javascript Full Project For Beginners

 

 

Now make a views folder inside the root directory and inside it make a pdftoaudio.ejs file and copy paste the following code

 

 

views/pdftoaudio.ejs

 

 

<!DOCTYPE html>
<html>
  <head>
    <title><%=title%></title>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    />
  </head>
  <body>
      <div class="container">
          <h1 class="text-center">
              PDF to Audio
          </h1>
          <br><br>
          <form id="form">
              <div class="form-group">
                  <label for="pdf">Upload PDF File:</label>
                  <input type="file" name="" id="upload-input" required accept=".pdf">
              </div>
              <div class="form-group">
                <label for="format">Select Language of Voice:</label>
                <select class="form-control" name="language" id="language">
                    <option value="af" selected>Afrikaans</option>
                    <option value="sq">Albanian</option>
                    <option value="ar">Arabic</option>
                    <option value="hy">Armenian</option>
                    <option value="ca">Catalan</option>
                    <option value="zh">Chinese</option>
                    <option value="zh-cn">Chinese (Mandarin/China)</option>
                    <option value="zh-tw">Chinese (Mandarin/Taiwan)</option>
                    <option value="zh-yue">Chinese (Cantonese)</option>
                    <option value="hr">Croatian</option>
                    <option value="cs">Czech</option>
                    <option value="da">Danish</option>
                    <option value="nl">Dutch</option>
                    <option value="en" selected>English</option>
                    <option value="en-au">English (Australia)</option>
                    <option value="en-uk">English (United Kingdom)</option>
                    <option value="en-us">English (United States)</option>
                    <option value="eo">Esperanto</option>
                    <option value="fi">Finnish</option>
                    <option value="fr">French</option>
                    <option value="de">German</option>
                    <option value="el">Greek</option>
                    <option value="ht">Haitian Creole</option>
                    <option value="hi">Hindi</option>
                    <option value="hu">Hungarian</option>
                    <option value="is">Icelandic</option>
                    <option value="id">Indonesian</option>
                    <option value="it">Italian</option>
                    <option value="ja">Japanese</option>
                    <option value="ko">Korean</option>
                    <option value="la">Latin</option>
                    <option value="lv">Latvian</option>
                    <option value="mk">Macedonian</option>
                    <option value="no">Norwegian</option>
                    <option value="pl">Polish</option>
                    <option value="pt">Portuguese</option>
                    <option value="pt-br">Portuguese (Brazil)</option>
                    <option value="ro">Romanian</option>
                    <option value="ru">Russian</option>
                    <option value="sr">Serbian</option>
                    <option value="sk">Slovak</option>
                    <option value="es">Spanish</option>
                    <option value="es-es">Spanish (Spain)</option>
                    <option value="es-us">Spanish (United States)</option>
                    <option value="sw">Swahili</option>
                    <option value="sv">Swedish</option>
                    <option value="ta">Tamil</option>
                    <option value="th">Thai</option>
                    <option value="tr">Turkish</option>
                    <option value="vi">Vietnamese</option>
                    <option value="cy">Welsh</option>
                </select>
            </div>
              <div class="form-group">
                  <button class="btn btn-block btn-danger">
                      Convert to Audio
                  </button>
              </div>
          </form>
      </div>
</body>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script>
    var language="en-us"
    $("#language").change(function(){
        language = $(this).children("option:selected").val();
    });
    var files
      $('#form').on('submit', function (e){
        e.preventDefault()
    //$('#upload-input').click();
    $("#button").text("Uploading File")
    $("#button").prop("disabled","true")
    $('.progress-bar').text('0%');
    $('.progress-bar').width('0%');
    convertFile()
});
$('#upload-input').on('change', function(){
  files = $(this).get(0).files;
  var fileExtension = ['pdf'];
        if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
           $(this).val("") 
    
swal ( "Oops" ,"Please Upload a PDF File",  "error" )

        }
})

function convertFile(){
  if (files.length > 0){
    // create a FormData object which will be sent as the data payload in the
    // AJAX request
    var formData = new FormData();
    // loop through all the selected files and add them to the formData object
    for (var i = 0; i < files.length; i++) {
      var file = files[i];
      // add the files to formData object for the data payload
      formData.append('file', file, file.name);
    }
    console.log(formData)
    var formdata2 = new FormData()
    $.ajax({
      url: '/uploadpdftoaudio',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(data){
          var data2 = {path:data.path,language:language}
          console.log('upload successful!\n' + data.path);
          $("#button").text("File Uploaded Now Processing")
          $("#button").prop("disabled",true);
          formdata2.append('path',data.path)
          $.ajax({
              url:'/pdftoaudio',
              type:'POST',
              data:JSON.stringify(data2),
              contentType: "application/json",
              dataType:"json",
      success:function(data){

        console.log(data)

          window.open('/download?path='+data.path)
          $("#button").text("Upload File")
          $("#button").prop("disabled",false);
          location.reload();
      }
          })
      },
      xhr: function() {
        // create an XMLHttpRequest
        var xhr = new XMLHttpRequest();
        // listen to the 'progress' event
        xhr.upload.addEventListener('progress', function(evt) {
          if (evt.lengthComputable) {
            // calculate the percentage of upload completed
            var percentComplete = evt.loaded / evt.total;
            percentComplete = parseInt(percentComplete * 100);
            // update the Bootstrap progress bar with the new percentage
            $('.progress-bar').text(percentComplete + '%');
            $('.progress-bar').width(percentComplete + '%');
            // once the upload reaches 100%, set the progress bar text to done
            if (percentComplete === 100) {
              $('.progress-bar').html('Done');
            }
          }
        }, false);
        return xhr;
      }
    });
  }
}
  </script>
</html>

 

See also  jsPDF Example to Open Generated PDF Document in New Window Using doc.output() in Browser Using Javascript Full Project For Beginners

 

 

Screenshot

 

 

 

 

 

Leave a Reply