Search This Blog

Latest Blog Posts

How To Extract Text From PDF Using JavaScript | PDF To Text Extractor

Source Code to extract text from pdf documents.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF to Text Extractor</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js" integrity="sha512-ml/QKfG3+Yes6TwOzQb7aCNtJF4PUyha6R3w8pSTo/VJSywl7ZreYvvtUso7fKevpsI+pYVVwnu82YO0q3V6eg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <style>
        h1{
            width: 100%;
            text-align: center;
        }
        .pdfwork,.afterupload{
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction:column;
            width: 100%;
        }
        .pdfwork *{
            margin-top: 5px;
        }
        .afterupload{
            display: none;
        }
        .another{
            display: none;
        }
    </style>
</head>
<body>
    <h1>PDF To Text Extractor</h1>
    <div class="pdfwork">
        <button class="another" onclick="location.reload()">Extract Another PDF</button>
        <span>Select PDF</span>
        <input type="file" class="selectpdf">
        <span>Password :</span>
        <input type="password" class="pwd" placeholder='optional'>
        <button class="upload">Upload</button>
        <div class="afterupload">
            <span>Select Page</span>
            <select class="selectpage" onchange="afterProcess()"></select>
            <a href="" class="download" download>Download Pdf Text</a>
            <textarea class="pdftext"></textarea>
        </div>
    </div>
    <script>
        pdfjsLib.GlobalWorkerOptions.workerSrc="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.worker.min.js";
        let pdfinput = document.querySelector(".selectpdf");
        let pwd = document.querySelector(".pwd");
        let upload = document.querySelector(".upload");
        let afterupload = document.querySelector(".afterupload");
        let select = document.querySelector("select");
        let download = document.querySelector(".download");
        let pdftext = document.querySelector(".pdftext");
        upload.addEventListener('click',()=>{
            let file = pdfinput.files[0];
            if(file!=undefined&&file.type=="application/pdf"){
                let fr = new FileReader();
                fr.readAsDataURL(file)
                fr.onload=()=>{
                    let res = fr.result;
                    if(pwd.value==""){
                        extractText(res,false)
                    }else{
                        extractText(res,true)
                    }
                }
            }else{
                alert("select a valid pdf file")
            }
        })
        let alltext = [];
        async function extractText(url,pass) {
          try{
            let pdf;
            if(pass){
                pdf = await pdfjsLib.getDocument({url:url,password:pwd.value}).promise;
            }else{
                pdf = await pdfjsLib.getDocument(url).promise;
            }
            let pages = pdf.numPages;
            for(let i=1;i<=pages;i++){
                let page = await pdf.getPage(i)
                let txt = await page.getTextContent();
                let text = txt.items.map((s)=>s.str).join("");
                alltext.push(text)
            }
            alltext.map((e,i)=>{
                select.innerHTML+=`
                <option value="${i+1}">${i+1}</option>
                `;
            })
            afterProcess()
          }catch(err){
            alert(err.message)
          }
        }

        function afterProcess(){
            pdftext.value=alltext[select.value-1];
            download.href="data:text/plain;charset=utf-8,"+encodeURIComponent(alltext[select.value-1])
            afterupload.style.display="flex";
            document.querySelector(".another").style.display="unset";
        }
    </script>
</body>
</html>

Javascript CRUD APP Using Google Sheet as a Database | Appscript Crud app

HTML, CSS, JavaScript code for Crud App Using Google Sheet as a Database


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .edit,.delete{
            background-color:red;
            cursor: pointer;
            color:white;
            padding: 3px;
            border-radius:5px;
        }
        .update{
            display: none;
        }
    </style>
</head>
<body>
    <form>
        <input type="text"class="todo"placeholder='Todo..'>
        <button class="add"type="button" onclick="addData()">Add Todo</button>
        <button class="update"type="button">Update Todo</button>
    </form>
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>Todo</th>
                <th>Update</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    <script>
        let api = "YOUR_API_URL_HERE";
        let form = document.querySelector("form");
        let add = document.querySelector(".add");
        let update = document.querySelector(".update");
        let tbody = document.querySelector("tbody");
        function addData() {
            add.textContent="Adding.."
            let obj = {
                todo:form[0].value
            }
            fetch(api,{
                method:"POST",
                body:JSON.stringify(obj)
            })
              .then(res => res.text())
              .then(data => {
                readData()
                alert(data)
                add.textContent="Add Todo"
                form.reset();
              });
        }

        function readData(){
            fetch(api)
            .then(res=>res.json())
            .then(data=>{
                let todo = data.todo;
                let trtd = todo.map(each=>{
                    return `
                    <tr>
                    <td class="id">${each[0]}</td>    
                    <td class="data">${each[1]}</td>
                    <td class="edit"onclick="updateCall(this,${each[0]})">Edit</td>    
                    <td class="delete"onclick="delData(${each[0]})">Delete</td>    
                    </tr>
                    
                    `
                })
                tbody.innerHTML=trtd.join("");
            })
        }
        readData()
        function delData(id){
            fetch(api+`?del=true&id=${id}`)
            .then(res=>res.text())
            .then(data=>{
                readData()
                alert(data)
            })
        }
        function updateCall(elm,id){
            add.style.display="none"
            update.style.display="unset"
            let todo = elm.parentElement.querySelector(".data").textContent;
            form[0].value=todo;
            update.setAttribute("onclick",`updateData(${id})`)
        }
        function updateData(id){
            update.textContent="Updating.."
            fetch(api+`?update=true&id=${id}&data=${form[0].value}`)
            .then(res=>res.text())
            .then(data=>{
                readData()
                alert(data)
                form.reset()
            update.textContent="Update Todo"
            add.style.display="unset"
            update.style.display="none"
            })
        }
    </script>
</body>
</html>


Appscript Code For CRUD APP using Google Sheet as a Database



const app = SpreadsheetApp.openByUrl("Your_Spreadsheet_url_here");
const sheet = app.getSheetByName("Sheet1");
function doGet(req){
if(req.parameter.del){
sheet.deleteRow(req.parameter.id)
return ContentService.createTextOutput("Data Deleted!")
}else if(req.parameter.update){
  sheet.getRange(req.parameter.id,2).setValue(req.parameter.data);
  return ContentService.createTextOutput("Data Updated!")
}else{
  let data = sheet.getDataRange().getValues();
data.shift()
let obj = {
  todo:data
}
  return ContentService.createTextOutput(JSON.stringify(obj))
}
}
function doPost(req){
  let data = JSON.parse(req.postData.contents)
  sheet.appendRow(["=row()",data.todo])
  return ContentService.createTextOutput("Data Received!")
}

function test(){
  Logger.log(sheet.getDataRange().getValues())
}

How To Integrate ChatGPT with Google Sheet

Code For Appscript

Paste Below Code In AppScript and Run the run function and in google sheet column type the custom =Chat("Your Questions Here") formula and press Enter.


const apiKey = "YOUR_OPEN_AI_API_KEY_HERE";
function run(){
Chat("Hello")
}
function Chat(question){
  let payload = {
  "model": "text-davinci-003",
  "prompt": `${question}`,
  "temperature": 0.7,
  "max_tokens": 256,
  "top_p": 1,
  "frequency_penalty": 0,
  "presence_penalty": 0
}
let options = {
  "method":"post",
  "headers":{
    "Authorization":"Bearer "+apiKey,
    "Content-Type":"application/json"
  },
  "payload":JSON.stringify(payload)
}
let req = UrlFetchApp.fetch("https://api.openai.com/v1/completions",options)
let res = JSON.parse(req).choices[0].text;
return res;
}


Upload Image to Google Drive And Google Sheet From HTML File Input Element | JavaScript | AppScript

Upload Image to Google Drive And Google Sheet From HTML File Input Element | JavaScript | AppScript

Hello, in today's video i'll be showing you how to upload image in Google drive and Google sheet From HTML File Input Element.

AppScript Code


let app = SpreadsheetApp.openByUrl("Your_Google_Sheet_URL");
let sheet = app.getSheetByName("Your_Google_Sheet_Name");
function doPost(e){
try{
  let obj = JSON.parse(e.postData.contents);
  let dcode = Utilities.base64Decode(obj.base64);
  let blob = Utilities.newBlob(dcode,obj.type,obj.name);
  let newFile = DriveApp.createFile(blob);
  let link = newFile.setSharing(DriveApp.Access.ANYONE_WITH_LINK,DriveApp.Permission.VIEW).getDownloadUrl();
  let lr = sheet.getLastRow();
  sheet.getRange(lr+1,1).setFormula(`=IMAGE("${link}")`);
  return ContentService.createTextOutput("image uploaded")
}catch(err){
  return ContentService.createTextOutput(err)
}

}

Html JavaScript Code


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<input type="file"accept="image/*">
<img src="" alt="">
<script>
    let url = "Api_Endpoint_Url";
    let file = document.querySelector("input");
    let img = document.querySelector("img");
    file.addEventListener('change',()=>{
        let fr = new FileReader();
        fr.addEventListener('loadend',()=>{
            let res = fr.result;
            img.src=res;
            let spt = res.split("base64,")[1];
            // console.log(spt);
            let obj = {
                base64:spt,
                type:file.files[0].type,
                name:file.files[0].name
            }
            fetch(url,{
                method:"POST",
                body:JSON.stringify(obj)
            })
            .then(r=>r.text())
            .then(data=>console.log(data))

        })
        fr.readAsDataURL(file.files[0])
    })
</script>
</body>
</html>

Convert HTML CSS to PDF with JavaScript | HTML to PDF

Convert HTML CSS to PDF with JavaScript | HTML to PDF Hello, in this video i will show you how to convert HTML, CSS to PDF using JavaScript and HTML2PDF.js library.

Source Code to Convert HTML to PDF


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML to PDF</title>
    <style>
        .elem {
            background-color: darkCyan;
            color: white;
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js" integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body>
    <div class="elem">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Sequi illo cumque ea velit, earum explicabo commodi ipsa voluptatem quidem dolores laborum eaque itaque nihil at eveniet similique fugit enim consequuntur, officia nostrum nemo! Nam voluptate corporis
        error aut nobis repellendus illo pariatur accusantium non quas dolores nihil dignissimos quam quisquam natus nostrum nesciunt officia temporibus doloremque, dolor iste! Aspernatur ad ratione perspiciatis sequi consequuntur aut nulla itaque consequatur.
        Aliquam fugit distinctio debitis deleniti, nisi nemo eius a, facilis dolorem tempora iusto laboriosam dicta beatae. Nisi, quisquam. Ducimus facere rerum veniam, reprehenderit labore expedita! Amet fuga, quia dicta excepturi iusto cumque.
    </div>
    <button class="download">Download PDF</button>
    <script>
        let div = document.querySelector(".elem");
        let btn = document.querySelector(".download");
        btn.addEventListener('click', () => {
            html2pdf().from(div).save()
        })
    </script>
</body>

</html>

Contact Us