Replacing System.Windows.Forms.WebBrowser with Microsoft.Web.WebView2.WinForms.WebView2 in WinForms apps

I am upgrading a WinForms C# .NET 4.8 Framework application and replacing the embedded browser System.Windows.Forms.WebBrowser with Microsoft.Web.WebView2.WinForms.WebView2. I’m invoking some browser-hosted JavaScript functions from my C# code, and also my JavaScript functions do invoke some C# methods.
I’ve made it working (one of the information sources was the article https://weblog.west-wind.com/posts/2021/Jan/14/Taking-the-new-Chromium-WebView2-Control-for-a-Spin-in-NET-Part-1#do-you-need-the-webview2), however, I’m not feeling comfortable with the serialization/deserialization in my code.

My question is: should I have realized the interaction between C# and JavaScript in a different way?

Here are two C# code fragments with JavaScript invocation from a WinForms test program I’ve produced to cope with the migration:

public struct ConfigGraph3D
{
    public bool showServices { get; set; }
    public string viewStyle { get; set; }
    public bool enforceNodeLabels { get; set; }
    public bool enforceServiceLabels { get; set; }
    public bool planesVisible { get; set; }
    public bool embedded { get; set; }
}
// retrieving a JavaScript structure into a C# structure
//var CONFIG = { showServices: true, viewStyle: "O", enforceNodeLabels: false, 
//               enforceServiceLabels: false, planesVisible: true, embedded: false};
//
string invocation = "getConfig()";
string response = await browser.ExecuteScriptAsync(invocation);
// Notice here that I’m deserializing the data twice: first removing backslash escapes
// then converting it into the structure ConfigGraph3D.
string configStr = JsonSerializer.Deserialize<string>(response);
ConfigGraph3D config = JsonSerializer.Deserialize<ConfigGraph3D>(configStr);
textConfig.Text = response;
//
// sending a graph structure to JavaScript. 
// The properly formatted JSON structure is read from a file by yet it needs to be serialized 
// in order to add escape backslash characters.
//
string invocation = getJsonFile (graphFilePath) ;
string response = await browser.ExecuteScriptAsync(invocation);
//
//
string getJsonFile (string graphFilePath)
{
    string contents = File.ReadAllText(graphFilePath);
    JsonSerializerOptions jso = new JsonSerializerOptions();
    jso.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
    string contents2 = JsonSerializer.Serialize(contents, jso);
    string invocation = "replaceModelList(" + contents2 + ")";
    return invocation;
}

Invoking C# from JavaScript example:


    public struct ItemSelectedInfo
    {
        public int id { get; set; }
        public string type { get; set; }
    }
    //
    // invoked from JavaScript 
    // var jsonObj = "{ "id": " + mesh._id2 + ", "type":"" + mesh._type + ""}";   
    // window.chrome.webview.hostObjects.sync.dotnet.SelectedinGraphic(jsonObj);
    //
    [ComVisible(true)]
    public class GraphInterface
    {
        public void SelectedinGraphic(string jsonInfo)
        {
            ItemSelectedInfo selectedNodeKey = JsonSerializer.Deserialize<ItemSelectedInfo>(jsonInfo);
            Debug.WriteLine("SelectedinGraphic: " + jsonInfo);
        }
    }


Proper way of dealing with returning from a fetch

I’m a bit new to coding in a JS/TS way and I just wanted to know the best practice when it comes to returning and handling void and values that come from a fetch. In short, I’d like to use fetch to retrieve a JSON file somewhere, extract some relevant info, and return a dict.

async function doSomething() {
    const response =  fetch(...)
    .then(response =>
        response.json().then(data => ({
            data: data,
            response: response.ok
        }))
    )
    .then(data => {
        if (!data.response) {
            console.warn("Response was not ok...")
            return null
        } else if (data.data["results"] == 0) {
            console.info("Returned no results")
            return null
        } else {
            const returned = {
                name: data.data["stuff"],
                thing: data.data["other"]
            }
            return returned
        }
    })
    .catch(error => console.error(`${error}`))

return response

TS returns an error saying that Property 'name' does not exist on type 'void | {...} when I want to use the values of the dict. The error, I completely understand. When using the function I try to do type checking to handle when it returns void, but it still raises an error for something like this:

const request = await getQuery("movie", query)
    if (request === undefined || request === null) return "I wasn't able to find your query."
    const data = {
        name: request.name
    }
}

I’m just wondering what’s the best way to write and handle void, and using the dict values.

how can i show a different window depending on the option i choose from a selection combo?

I have this selection in HTML:

    <p>Selecciona el tipo de cita que desee: </p>
    <select id = "specialityAppointmentSelection">
      <option value = "1">Medicina</option>
      <option value = "2">Enfermería</option>
    </select>

And I want to show a different message when I click in one of this. I try this in javascript:

document.getElementById("specialityAppointmentSelection").addEventListener('onchange', function(){
     let specialityAppointmentSelection = document.getElementById("specialityAppointmentSelection");
     let specialityOption = specialityAppointmentSelection.value;
     console.log(specialityOption);
    if(specialityOption === "1"){
        console.log("medicina");
    } else {
        console.log("enfermería");
    }
 });

But I can’t show anything in my console.log, what is the problem?

How to recognize Id attribute in rails form_tag?

I am using a form in rails to pass an id. That id will trigger the javascript Sweet Alert function which will pop up a modal with a confirmation message. When the message is confirmed “Yes” user will have their account deleted meaning will be redirected to the rails route. That is what’s supposed to happen. I cannot get the id to trigger in the form and bring up the modal, but the routing is working perfect. Let me show you two ways I tried to accomplish this.

Ruby on Rails

<%= form_tag(registration_path(current_user), {method: :delete}) do %>
 <%= hidden_field_tag('deleteBtn') %>
 <button type="submit"><i class="fa fa-trash"></i>Delete Account</button>
<% end %>

Javascript using Sweet Alert

$('#deleteBtn').on('click', function(e) {
          e.preventDefault();
          swal({
              title: 'Decline Inquiry',
              text: 'Are you sure you want to delete your account? This will delete all records of your entire account.',
              icon: 'warning',
              buttons: [ 'Yes', 'No']
          }).then(isNo => {
              if(isNo) return;
              $('#deleteBtn').submit();
          });
      });

Please understand I have tried several variations of form_tag and the html id won’t even show up when I inspect it:

<%= form_tag 'registration_path(current_user)', ({method: :delete, id: "deleteBtn"}) do %>
 <button type="submit"><i class="fa fa-trash"></i>Delete Account</button>
<% end %>

Now something to note, I can drop the form and just use the button passing an id and the modal works, but accessing the rails route in Javascript fails and I get a routing error message.
I just replaced the

$('#deleteBtn').submit(); 

with

$.get('<%= link_to registration_path(current_user), method: :delete, class: 'delete' do %><% end %>');

or

window.location.pathname('<%= link_to registration_path(current_user), method: :delete, class: 'delete' do %><% end %>');

I have been working on this a whole day now and any help is appreciated. Since I can’t access the rails routes in Javascript my only option is to use a form.

Version: Rails 4.2.4

Want to run js in loop

var pause = document.querySelector(".pause1");
var audio = document.querySelector(".audio1");

function togglePlay() {
  if (audio.paused) {
    audio.play();
    pause.innerHTML = "🔊";
  } else {
    audio.pause();
    pause.innerHTML = "🔇";
    pause.style.color = " #a80000";
  }
}
<li class="mp3-views">
  <div class="views-field mp3-play">
    <div class="pause1" onclick="togglePlay()">▶</div>
    <div class="player">
      <audio class="audio1" src="assets/images/audio.mp3" type="audio" loop=""></audio>
    </div>
  </div>
</li>

I want to run this code in loop because Play button is repeated in ‘li’ and I am not sure how to do it

Uncaught ReferenceError. Firebase SDK not recognised despite correct order of script tags

I am trying to implement firebase authentication on my website. However, whenever I try to test the function, I get the following error:

Uncaught ReferenceError: createUserWithEmailAndPassword is not defined

It will produce the applicable ReferenceError for any Firebase SDK function I try to use.

A common problem most people point out is not ordering the script tags correctly, however, mine seem fine to me:

<script type="module">
    // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-analytics.js";
    import { getAuth, createUserWithEmailAndPassword} from "https://www.gstatic.com/firebasejs/9.8.1/firebase-auth.js";
    import { getFirestore } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-firestore.js"

    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries

    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
      apiKey: "xxxxxx",
      authDomain: "xxxxxx",
      projectId: "xxxxxx",
      storageBucket: "xxxxxxx",
      messagingSenderId: "xxxxxxx",
      appId: "xxxxxxxx",
      measurementId: "xxxxxx"
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
    const auth = getAuth(app);
    const db = getFirestore(app);
  </script>

<script src="scripts/auth.js"></script>
<script src="scripts/index.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>

I am absolutely stumped as to what might be causing this, any input would be extremely appreciated.

Edit: I have identified that the script tags execute in the wrong order, printing to console occurs first in auth.js, then in the Firebase intialisation script. How would I ensure they execute in the correct order?

Not being able to copy URL to Clipboard without adding the protocol https

I am fairly new in working with ASP.NET and Javascript. Recently I came across this problem where I had to copy the URL on a javascript button action and paste on a new tab to visit the website. It does work locally but not on the live server. I found out that it was due to not adding ‘https’. Is there any way where it can work without using ‘https’ like ‘http’ only?

function CopyTextFunction() {
                const params = new URLSearchParams(window.location.search);
                params.get('ID')
                var copyText = "https://randomshop.net/OnlineShop/ShopProducts?ID=" + params.get('ID');
                console.log(copyText);
                navigator.clipboard
                  .writeText(copyText)
                  .then(() => {
                      alert("successfully copied");
                  })
                  .catch(() => {
                      alert("something went wrong");
                  });
            }

How to avoid duplicate JS code that each uses its own this?

I have several different classes with the same duplicate code. Aside from the different identity of each’s this, these duplicate code are all ostensibly identical.

Here’s a simplified example:

class classA {
  ...

  doSomething() {
    if (!this.id || !this.data || !this.isAllowed()) {
      return null;
    }
    return someImportedFunc(this.data, this.metadata, this.doSomethingElse());
  }
}

class classB {
  ...

  doSomething() {
    if (!this.id || !this.data || !this.isAllowed()) {
      return null;
    }
    return someImportedFunc(this.data, this.metadata, this.doSomethingElse());
  }
}

// Many other classes like this

I’ve thought of moving the doSomething method to another class, then importing it in all these classes. But that would result in a very messy method that takes many, many arguments to account for all the different this‘s. It’d look like doSomething(id, data, metadata, isAllowed, doSomethingElseResult) { ... }, except with like 15 args instead of 5 since this is a simplified example.

How can I avoid duplicate code in this kind of situation?

How to align (input[type=”checkbox”]+Label) to center horizontally on the page?

I am learning HTML ,CSS & JS, and I am stuck here.

I want to align the checkbox and label to the center of the page and no matter what I try,
it’s misaligned, can someone explain what am I doing wrong here.

Night Mode On is misaligned

   <!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>
        @import url('https://fonts.googleapis.com/css2?family=Righteous&display=swap');

        @import url('https://fonts.googleapis.com/css2?family=Amatic+SC:wght@700&display=swap');


        body{
            font-family: 'Righteous', cursive;
            /* font-family: 'Amatic SC', cursive; */
            font-size: 1.3em;
            color: white;
            background-color: black;
        }

        /* making the font style same */
        input,button{
            font-family: inherit;
        }
        
        /* styling the field set and aligning to center */
        fieldset{
            max-width: max-content;
            background-color: black;
            margin-left: auto;
            margin-right: auto;
        }


        /* night mode */

        /* to hide the defualt checkbox and align it to middle */
        .toggle{
            vertical-align: middle;
            opacity:0;
        }

        /* giving  night image for checkbox */
        .toggle + label{
            background:url(night.png) left center no-repeat;
            background-size: 1.5em;
            padding-left: 1.5em;
        }

        /* giving day image for checkbox */
        .toggle:checked + label{
            background:url(day.png) left center no-repeat;
            background-size: 1.5em;
        }

        
        /* to align the checkbox and label to center, kinda works? but this just sends it more towards left*/
        .aligner{
            position: relative;
            margin-left: 50vw;
            margin-right: 50vw;
        }
        
        /* night/day toggle ends */
    </style>
</head>

<body>
<form>
    <!-- to align the checkbox and label -->
    <div class="aligner">
        <input type="checkbox" id="toggle" class="toggle" onclick="darkMode();">
        <!-- added no breaking space becuase it was breaking -->
        <label for=toggle id="toglab">Night&nbsp;Mode&nbsp;On</label>
    </div>

    <!-- main form -->
    <fieldset id="fieldset">
        <legend>Sign In</legend>
        <!-- email -->
            <label for="email">Email:</label>
            <br>
            <input type="email" name="email" id="email">
            <br><br>
        <!--email  -->

        <!-- password -->
            <label for="password">Password:</label>
            <br>
            <input type="password" id="password">
            <br>
        <!-- password -->
        <!-- show password -->
            <br>
            <label for="checkbox" id="showpass">Show Password:</label>
            <input type="checkbox" id="checkbox" onClick=showPass();>
        <!-- show password -->
            <br><br>
          
            <!-- Submit -->
            <button type="submit">Submit</button>
    </fieldset>
</form>  

<!-- js starts -->
    <script>
        function showPass(){
            var x=document.getElementById("password");
            var y=document.getElementById("showpass");
            if(x.type=="password"){
                x.type="text";
                y.innerHTML="Hide Password";
            }
            else{
                x.type="password";
                y.innerHTML="Show password";
            }
        }

        function darkMode(){
            var a=document.getElementById("toglab");
            var b=document.getElementById("toggle");
            var body=document.body;
            var fieldset=document.getElementById("fieldset");
            if(b.checked==true){
                a.innerHTML="Day&nbsp;Mode&nbsp;On";
                body.style.backgroundColor="white";
                body.style.color="black";

                fieldset.style.backgroundColor="white"
            }
            else{
                a.innerHTML="Night&nbsp;Mode&nbsp;ON";
                body.style.backgroundColor="black";
                body.style.color="white";
                
                fieldset.style.backgroundColor="black"
            }
        }
    </script>

    <!-- js ends  -->
</body>
</html>

Sorry to paste the long code, but I hope I have provided everything possible.
I have tried some of the previous questions methods,
like display-inline, display-flexbox, etc but none of them seems to work.

Used the Div to align the Night Mode On text to center, also used nbsp; or else it was breaking.

I want to display fetched data from api in form columns (auto fill data) in React.js and Mysql

i am using onKeyUp event for fire api without submitting the form and i fetched data in response successfully if Mobile number matched. But i don’t understand how to display these data as a default value in columns. i also try to do this in useState default value but it doesn’t work.

Please help me. Thank you!

Here is my code of frontend.

import React, { useEffect, useState } from 'react'
import { Alert } from 'react-bootstrap';
import { useForm } from 'react-hook-form';

const Billing = () => {

    const [fill, setFill] = useState(false);
    const [success, setSuccess] = useState(false);
    const [customerDataFill, setCustomerDataFill] = useState()
  
    const {
      register,
      handleSubmit,
      formState: { errors },
    } = useForm();

   

    const [bill, setBill] = useState({
      contactNo: "",
     
    });

    const OnKeyUpFunc = () =>{
      const { contactNo } = bill; 
  
          axios.post("http://localhost:5000/getCustomerDetails", {
            contactNo: contactNo,
          })
          .then((Rres) => {
            setCustomerDataFill(Rres.data)
            console.log(Rres.data, "<<<<-----This is customer details testing...");
          }); 
      }


//**I WANT TO DISPLAY THIS FETCHED CUSTOMER NAME IN CUSTOMER NAME COLUMN**

      const GetCustNameFill = customerDataFill && customerDataFill.map((cData) => cData.Cust_Name)


      const [customerName, setcustomerName] = useState("")
      console.log(GetCustNameFill,"----<><><> GetCustNameFill fetch name checking")

    const handleCustNameChange = (e) => {
      setcustomerName(e.target.value);
      // console.log(e, "this is e check...");
    };

    let name, value;
    const handleInputs = (e) => {
      console.log(e);
      name = e.target.name;
      value = e.target.value;
  
      setBill({ ...bill, [name]: value });
      setFill(false);
    };
  
    const onclick = async (e) => {
      // e.preventDefault();
      const {  contactNo  } =
        bill;
  
      try {
        if (
            customerName === "" ||
            contactNo === "" 
            
        ) {
          setFill(true);
          setSuccess(false);
        } else {
          setFill(false);
          const config = {
            header: {
              "Content type": "appication/json",
            },
          };
  
          const { data } = await axios.post(
            "http://localhost:5000/billing_data",
            {   
              cust_name : customerName,
              contact_no : contactNo,
             
            },
            config
          );
  
          console.log(data);
          localStorage.setItem("Billing_details", JSON.stringify(data));
          setSuccess(true);
        }
      } catch (error) {
        console.log(error);
      }
    };

return ( <>

    <div className="modal fade" id="modalCenter" tabindex="-1" aria-hidden="true">
                          <div className="modal-dialog modal-dialog-centered modal-lg" role="document">
                            <div className="modal-content">
                              <div className="modal-header">
                                <h5 className="modal-title" id="modalCenterTitle">Bill information</h5>
                                <button
                                  type="button"
                                  className="btn-close"
                                  data-bs-dismiss="modal"
                                  aria-label="Close"
                                ></button>
                              </div>

                              <form onSubmit={handleSubmit(onclick)} method="POST">
                  {fill && (
                    <div className="container mt-3">
                      <Alert variant="danger" style={{ fontSize: 15 }}>
                        <strong > Please Fill All the Required Field!</strong>
                      </Alert>
                    </div>
                  )}

                  {success && (
                    <div className="container mt-3">
                       <Alert variant="success" style={{ fontSize: 15 }}>
                        <strong style={{color:"green"}}>Bill Added Successssfully!</strong>
                      </Alert>
                    </div>
                  )}

                  {errors.contact && (
                    <div className="container mt-3">
                      <Alert variant="danger" style={{ fontSize: 15 }}>
                        <strong>{errors.contact.message}</strong>
                      </Alert>
                    </div>
                  )}
                  
                  {errors.email && (
                    <div className="container mt-3">
                      <Alert variant="danger" style={{ fontSize: 15 }}>
                        <strong>{errors.email.message}</strong>
                      </Alert>
                    </div>
                  )}
                              <div className="modal-body">
                              <div className="row  g-2">
                              <div className="col mb-2">
                                    <label for="nameWithTitle" className="form-label">Contact No.</label>
                                    <input
                                      type="text"
                                      id="nameWithTitle"
                                      className="form-control"
                                      placeholder="Enter Contact no."
                                      value={bill.contactNo}
                                      onChange={handleInputs}
                                      name="contactNo"
                                      onKeyUp={OnKeyUpFunc}
                                    />
                                  </div>

                              <div className="col mb-2">
                                    <label for="emailWithTitle" className="form-label">Customer name</label>
                                    <input
                                      type="text"
                                      id="emailWithTitle"
                                      className="form-control"
                                      placeholder="Enter Customer Name"
                                      value={customerName}
                                      onChange={handleCustNameChange}
                                      defaultValue={GetCustNameFill}
                                    />
                                  </div>

                                 
                                </div>

                               


                              </div>
                              <div className="modal-footer">
                                <button type="button" className="btn btn-outline-secondary" data-bs-dismiss="modal">
                                  Close
                                </button>
                                <button type="submit" className="btn btn-primary">submit</button>
                              </div>
                             </form>
                            </div>
                          </div>
                        </div>
  </>
  )
}

export default Billing

** Here is Backend Code**

var express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mysql = require("mysql");
const expressAsyncHandler = require("express-async-handler");
const generateToken = require("./jwtToken/generateToken");
const bcrypt = require("bcryptjs");

const db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "star_battery_db",
});

db.connect((err) => {
  if (err) {
    console.warn("Error in connection, Check XAMPP server");
  } else {
    console.warn("MySql db connected");
  }
});

app.use(cors());
app.use(express.json()); 
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(5000, () => console.log("Server is running on 5000"));

// Api for fetch Partcular customer data for billing.
app.post("/getCustomerDetails",expressAsyncHandler(async (req, res) => {
  const contactNo = req.body.contactNo

  const users = `SELECT * FROM cust_master WHERE Contact= ${db.escape(contactNo)}`;
  db.query(users, (err, result) => {
    if (err) {
      res.status(404).send(err);
    }
    res.status(201).send(result);
  });
})
); ```

I have a Quiz Code and I Want to add more element in them

Hello friends I have a Quiz Code and I Want to add more element in them Like – confetti animation when click on right answer , rise wrong sound track when click on wrong answer,Final score of user and shuffle question

<!DOCTYPE html>
<html>
   <head>
                <link rel="stylesheet" type="text/css" href="https://sharecodepoint.in/sharecodepoint-website-data/quizze-files/sharecodepoint.css" />
                
    <script src="https://sharecodepoint.in/sharecodepoint-website-data/quizze-files/jquery-1.9.1.min.js"></script>
    
     <script type="text/javascript">
 $(document).ready(function() {
    $('label').click(function() {
        $('label').removeClass('worngans');
        $(this).addClass('worngans');
    });
});
 </script>
   
    
   </head>
   <body >
<div class="scp-quizzes-main">
<div class="scp-quizzes-data">
  <h3>1. What is your name ?</h3>
    
<br/>
    <input type="radio" id="python" name="question1">
       <label for="python">1.python</label><br/>
    <input type="radio"  name="question1">
       <label>2. java</label><br/>
    <input type="radio" name="question1">
       <label>3. html</label> <br/>
    <input type="radio" name="question1">
     <label>4. Django</label>
 </div>
 <div class="scp-quizzes-data">
  <h3>2. Are You my friend?</h3>
<br/>
    <input type="radio" name="question2">
       <label>1.Python</label><br/>
    <input type="radio"  name="question2">
       <label>2. Pyramid</label><br/>
    <input type="radio" name="question2" id="Css">
       <label for="Css">3. Css</label> <br/>
    <input type="radio" name="question2">
     <label>4.Django</label>
 </div>
</div>
</html>

unhiding a h1 tag on the clic of a button

I am creating a to-do list. I want to unhide a h1 tag on the click of a button. But it is not working. could anyone take a look at this code.

let a;

// #create is a button. I want to unhide the h1 tag on the click of this button.
let create = document.querySelector("#create");

// #box is the h1 tag. I want to unhide this h1 tag on the click of #create.
let box = document.querySelector("#box");


create.onclick = ()=>{
    
// I not only want to unhide box but also want to hide create button
create.style.display = "none";

    // Asking the user how many list does they have.
    a = prompt("Enter the number of list you have");

    // if 'a' is 1, I only want to unhide one h1 tag. So unhiding box if a is equal to 1.
    switch (a){
        case a==1:
            box.style.display = "block";
    }
}

Here this code is not working. Everything is working. It is hiding the button, It is asking the user how many list does they have and all. But It is not unhiding box. Also it is not showing any errors. What is wrong in this code. How can I unhide the box. Could anyone tell me what should i do here.

HTML:

<!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>
    <link rel="stylesheet" href="todolist.css">
</head>

<body align="center">
    <button id="create">create</button>
    <script src="todolist.js"></script>
    <p>
        <h1 id="box" style="display: none;">
            1
        </h1>

        <h1 id="box1" style="display: none;">
            2
        </h1>
       <h1 id="box2" style="display: none;">
            3
       </h1>
       <h1 id="box3" style="display: none;">
            4
       </h1>
       <h1 id="box4" style="display: none;">
            5
       </h1>
       <h1 id="box5" style="display: none;">
            6
       </h1>
       <h1 id="box6" style="display: none;">
            7
       </h1>
       <h1 id="box7" style="display: none;">
            8
       </h1>
       <h1 id="box8" style="display: none;">
            9
       </h1>
       <h1 id="box9"style="display: none;">
           10
       </h1>

</p>

How do I fit the entire component when printing it to PDF?

I am using jspdf and html2canvas. Printing the component would make the footer go to the next page.

How can I set this where it will dynamically resize to fit it on one page when I print it to pdf? Is this possible where the entire component will fit in one page only?

  //generate PDF
  const generatePdf = () => {
    // var doc = new jsPDF("p", "mm", "a4");
    var doc = new jsPDF("portrait", "pt", "a4");

    doc.html(document.querySelector("#pdf"), {
      html2canvas: {
        // insert html2canvas options here, e.g.
        width: 200,
        scae: 0.5,
      },
      callback: function (pdf) {
        pdf.save(`${id}.pdf`);
      },
    });
  };


<div>
      <Button
        variant="contained"
        style={{ float: "right" }}
        onClick={() => generatePdf()}
      >
        Print
      </Button>
      <Grid container justify="center" id="pdf" style={{ margin: "1rem" }}>
        <Grid item xs={12} style={{ padding: "8px" }}>
          <Grid item xs={12}>
            <Stack direction="row" spacing={2}>
              //logo here
              //title>
            </Stack>
           //Details here
                  {/* ----------------------------------------------------------------- */}
                  <Divider />
                  <TableContainer>
                   //Table here
                  </TableContainer>
                </div>
              ))}
          </Grid>
          {/* -------------------------------------------------------------- */}

          <div
            style={{
              textAlign: "center",
              marginTop: "2rem",
              marginBottom: "1rem",
              margin: "1rem",
            }}
          >
            //footer
          </div>
        </Grid>
      </Grid>