Converting axios to useFetch Nuxt 3

The problem i am encountering is that i started a project , and i build the entire API call using axios. Since i am in Nuxt 3 , i am trying to convert it to useFetch. I am encountering a problem , and one is that when i reload the page , the data is not fetched again when i am using useFetch.

This is my ApiService.js (converted to useFetch) :

import { useUserStore } from "~/store/user";
import qs from "qs";

class ApiService {
    constructor(baseURL) {
        this.baseURL = baseURL;
    }

    async apiRequest(method, url, data = null, options = {}, returnData) {
        const store = useUserStore();
        const requestUrl = `${this.baseURL}/${url}`;
        const params = options.params ? `?${qs.stringify(options.params, { arrayFormat: 'comma' })}` : '';

        try {
            // Make the request using useFetch
            const { data: responseData, error, status } = await useFetch(`${requestUrl}${params}`, {
                method,
                body: data,
                credentials: options.withCredentials ? 'include' : 'omit',
                headers: {
                    'Content-Type': 'application/json',
                },
            });

            if (error.value) {
                // Handling specific error statuses based on error.value
                const errorStatus = error.value.response?.status || 500;
                const errorReturnObj = {
                    status: errorStatus,
                    message: error.value.response?._data || error.value.message,
                };

                // Handling specific error codes
                if (errorStatus === 401) {
                    console.error("Expired token");
                    store.showSnackbar("Token-ul a expirat/Access neautorizat!");
                    navigateTo('/user/logout');
                } else if (errorStatus === 400) {
                    return returnData ? errorReturnObj : -2;
                } else if (errorStatus === 515) {
                    return returnData ? errorReturnObj : -3;
                } else if (errorStatus === 404) {
                    return returnData ? errorReturnObj : -4;
                }
                console.error(error.value.message || error.value.response?.status);
                return 0;
            }

            console.log("data parameter",data)
            console.log("responseData",responseData.value)


            // Success response handling
            const returnObj = {
                status: status,
                message: responseData.value
            };

            if (returnData === null) {
                return returnObj;
            }
            return returnData ? responseData.value : 1;

        } catch (error) {
            console.error(error);
            return 0;
        }
    }

    get(url, returnData = false, isBlob = false, isAnonymous = false, params = {}) {
        const options = {
            params,
            ...(isAnonymous ? { withCredentials: false } : { withCredentials: true }),
        };
        return this.apiRequest("GET", url, null, options, returnData);
    }

    post(url, data, returnData = false, isAnonymous = false) {
        const options = isAnonymous ? {} : { withCredentials: true };
        return this.apiRequest("POST", url, data, options, returnData);
    }

    put(url, data, returnData = false, isAnonymous = false) {
        const options = isAnonymous ? {} : { withCredentials: true };
        return this.apiRequest("PUT", url, data, options, returnData);
    }

    delete(url, data = null, returnData = false, isAnonymous = false) {
        const options = isAnonymous ? {} : { withCredentials: true };
        return this.apiRequest("DELETE", url, data, options, returnData);
    }
}

export default ApiService;

This is Products.js :

import ApiService from "./ApiService"

class ProductsService extends ApiService{
    constructor(){
        super("http://localhost:5043/api/product")
    }

    /**
     * @param {int?} pageNumber [The page number of with the current products]
     * @param {Array<string>} productTypes [The array of product types to filter]
     * @param {Array<string>} colorTypes [The array of color types to filter]
     * @param {Array<string>} widthRange [The array of product dimensions width to filter]
     * @param {Array<string>} heightRange [The array of product dimension height to filter]
     * @param {Array<int>} priceRange [The array of product price to filter]
     * @param {boolean} reverseFace [The type of reverse face (true or false)]
     * @returns {List} [The list with a limit of 15 products]
     */
    
    getProductsForUsers(pageNumber , productTypes , colorTypes, productDimensions, productPrice , productReverseFace, currency){
       
        const params = {
            productTypes,
            colorTypes,
            productDimensions,
            productPrice,
            productReverseFace
        }
        return this.get(`paginated/${pageNumber}/${currency}` , true , false , true , params) 
    }

    /**
     * @param {NONE}
     * @returns {Object
     * {
     *      filterColors : IMutableHashSet(ReadOnly),
     *      filterProductTypes : IMutableHashSet(ReadOnly)
     * }}
     *  [The class with the filter options - color and productTypes]
     */
    
    getFilterOptions(currency = "RON"){
        return this.get(`filterOptions/${currency}` , true , false , true) 
    }

    /**
     * @param {String} productCode [The product code]
     * @param {String} productType [The type of the product]
     * @param {String} currency [The current currency : RON or EUR]
     * 
     * @returns {Object{
     *      - integer : 1 or 0 (depends on succes)
     *      - productData : class (null if product has not been found )
     * }}
     */

    getProductData(productCode , productType, currency){
        console.log('IN PRODUCTS.JS',this.get(`${productCode}/${productType}/${currency}` , true , false, true))
        return this.get(`${productCode}/${productType}/${currency}` , true , false, true)
    }

    /**
     * @param {FormData} form [The form with the review info]
     * @returns {KeyValuePair<int,string>} [The info about the succefullness of the request]
     */

    postProductReview(form){
        return this.post('postReview' , form , false , false);
    }
}

export default new ProductsService()


And here i call getProductData in my .vue file:


const getProductData = async () => {
    const response = await productService.getProductData(productCode,productType , selectedCurrency.value);
    console.log("IN GET PRODUCT DATA" , response)
    if(response === -4){
        navigateTo(localePath('/error/notFound'))
    }else if(response === -2){
        navigateTo(localePath('/error/generalError'))
    }

    Object.assign(product.value , response)
    console.log(product.value)
    if (product.value.culoriProdus && product.value.culoriProdus.length > 0) {
        // Set the default color as the first color available
        selectedColor.value = {
           name : product.value.culoriProdus[0].numeCuloareDto,
           colorCode: product.value.culoriProdus[0].codCuloareDto
        };
        activeButtonColors.value = 0;
        filterImagesByColor(selectedColor.value.name);
    }
    if(product.value.dimensiuniProdus && product.value.dimensiuniProdus.length > 0){
        dimensionsLength.value = product.value.dimensiuniProdus.length;
        selectedDimension.value = { 
            width: product.value.dimensiuniProdus[0].lungimeDto,
            height: product.value.dimensiuniProdus[0].latimeDto,
            price :  product.value.dimensiuniProdus[0].pretDto,
            priceDiscount:  product.value.dimensiuniProdus[0].pretRedusDto
        }
        activeButtonDimensions.value = 0;
    }
    if(product.value.reviewsProdus){
        reviewsLen.value = product.value.reviewsProdus.length
    }
}

/* missing code */

onBeforeMount(async () => {
    getCurrentLocale()
   await getProductData()
  
})
</script>

multiple incarnations of “same” variable in JS local scope – chrome debugger

Have a look a this loop in javascript, and what is showing in the debugger. for some reason there are 4 occurrences of the item variable, however there should be only 1 (unless it seems I’m missing something).

You can see on the right side filteredAttributes.values is an array with 1 object. It gets sorted and mapped, the first time into the inner loop, when setting a breakpoint reveals unexpected values.

What is going on here?!

multiple variable occurrences

{filteredAttribute?.values.length > 0 ? (
  filteredAttribute?.values
    .sort((a, b) => a.fmOrder - b.fmOrder)
    .map((item, i) => {

PayPal Button Not Responding After Clicking “Pay” – React Integration

I’m integrating PayPal into my React app using the @paypal/react-paypal-js library, and I’m encountering an issue. When I click the “Pay” button after entering all payment details, nothing happens—the payment process doesn’t proceed, and no confirmation or error message appears.

The rest of the PayPal setup, including creating the order, works without issues. However, the final “Pay” button click doesn’t trigger any action, and there are no visible errors. I’ve tried several troubleshooting steps, but I’m not sure what else to check.

Here’s the code for my PayPal component:

import { clientId, ROOT_URL } from "../utils/constants";
import { useState } from "react";

const PayPalComponent = ({ amount, handlePayment }) => {
const [orderId, setOrderId] = useState(null);

return (
  <PayPalScriptProvider options={{ "client-id": clientId, currency: "USD", components: "buttons,funding-eligibility" }}>
    <div>
      <h2>Complete Payment</h2>
      <PayPalButtons
        fundingSource={FUNDING.CARD}
        createOrder={async (data, actions) => {
          try {  
            const order = await fetch(
              `${ROOT_URL}/paypal/create-order`,
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({ amount: amount }),
              }
            );  
            const result = await order.json();
            if (result.status === "success") {
              setOrderId(result.data.id);
              return result.data.id;
            }
          } catch (error) {
            console.error("Error creating order:", error);
            throw error;
          }
        }}
        onApprove={async (data, actions) => {
          try {
            if (orderId) {
              const order = await fetch(
                `${ROOT_URL}/paypal/capture-order/${orderId}`,
                {
                  method: "POST",
                  headers: {
                    "Content-Type": "application/json",
                  },
                }
              );  
              const result = await order.json();
              console.log(result, "Results");
              if (result.status === "success") {
                handlePayment(true, orderId, data.payerID);
              }
            }
          } catch (error) {
            console.error("Error capturing order:", error);
            throw error;
          }
        }}
        onError={(err) => {
          console.error("Payment Error:", err);
        }}
        style={{ layout: "vertical" }}
        funding={{ disallowed: [FUNDING.PAYPAL] }}
      />
    </div>
  </PayPalScriptProvider>
);
};

export default PayPalComponent;```


Troubleshooting Steps I’ve Tried
Checked Browser Compatibility:

I tried different browsers and cleared the cache and cookies to ensure there were no issues caused by outdated or cached data.
I also checked that my browser's pop-up blocker was disabled to ensure that PayPal could open necessary pop-ups for payment.
Checked Developer Console for JavaScript Errors:

There are no JavaScript errors in the console when I click the "Pay" button, which makes it difficult to debug the issue.
PayPal Account Settings:

Verified that my PayPal account is active and that it supports the currency being used in the app.
Tried Different Devices and Browsers:

Tested on multiple devices and browsers to ensure the issue wasn't device-specific, but the problem persists.
Updated PayPal SDK:

I confirmed that my @paypal/react-paypal-js package is up-to-date to avoid issues due to outdated code.
Checked Network and Internet Connection:

Verified that the internet connection is stable during testing, so network interruptions are unlikely to be the cause.

Cannot find module or its corresponding type declarations in a deno project

I recently started exploring deno. I wanted to run a script and write data into a file and save it in a folder. In that case I used fs-extra. Even if I install the package, i am getting the error “Cannot find module ‘npm:fs-extra’ or its corresponding type declarations

Installation command I used:
deno install npm:fs-extra

deno.json file:

  "tasks": {
    "dev": "deno run --watch main.ts"
  },
  "imports": {
    "@std/assert": "jsr:@std/assert@1",
    "fs-extra": "npm:fs-extra@^11.2.0",
    "mongodb": "npm:mongodb@^6.10.0"
  }
}

I imported it to the main.ts like this:
import fs from 'npm:fs-extra';

I tried using this way as well:
import fs from 'fs-extra';

But neither way worked out

Variables in JavaScript

I’m just wondering if it’s possible to exclude the “var” part when creating a variable in JavaScript. For example if I were to type “var greeting = hi” could I just say “greeting = hi” like in Python?
Thanks.

Dataform js publish() dependency declaration doesn’t work

I have a source file definitions/source/tiktok/advertiser.sqlx with the following declaration:

config {
    type: "declaration",
    schema: "tiktok_ads",
    name: "advertiser",
    description: "All advertising accounts from Tiktok"
}

I am trying to define a table with javascript using the below:

publish("tiktok2", {
    schema: "sample_schema",
    type: "table",
    dependencies: (["tiktok_ads.advertiser"]),
    description: "table description"
}).query(ctx => `
      SELECT
        advertiser.name AS campaign_advertiser
      FROM
        tiktok_ads.advertiser advertiser
`)

However the dependendencies propery is generating an error (Missing dependency detected: Action "the-brand-usa.sample_schema.tiktok" depends on "{"name":"tiktok_ads.advertiser","includeDependentAssertions":false}" which does not exist).

I know the table exists and the source file is declared properly because if I replace the query to use ref() then METADATA displays the dependency properly and the whole workspace compiles properly without errors.

      SELECT
        advertiser.name AS campaign_advertiser
      FROM
        ${ctx.ref("tiktok_ads", "advertiser")} advertiser

No task registered for key ReactNativeFirebaseMessagingHeadlessTask react native expo 51 with expo route

Question: Hi, I am using React Native with Expo SDK 51 and Expo Router. For notifications, I am using FCM v1. I receive notifications when my app is in the foreground, background, and even when it’s in a killed state. Additionally, when I click on a notification, it redirects me to the specific chat or post as expected.

However, I am facing an issue when my app is in a killed state. If I receive multiple notifications (e.g., 5 notifications) and try to open each one individually, nothing happens. But when I collapse all the notifications and then click on them, the app opens, although it fails to route to the intended destination.

Could someone please help me resolve this issue?

My project structure is like this:

app/

|-- index.jsx

|-- _layout.jsx

My index.jsx is like this:

const index = () => {
  return <></>;
};

export default index;

And this is my _layout.jsx

import * as Notifications from "expo-notifications";
import messaging from "@react-native-firebase/messaging";
import React, { useEffect, useState } from "react";
import { Stack, useRouter } from "expo-router";

Notifications.setNotificationHandler({
  handleNotification: async () => {
    const isOnChatPage = useAppStateStore.getState().isOnChatPage;
    return {
      shouldShowAlert: !isOnChatPage,
      shouldPlaySound: true,
      shouldSetBadge: false,
    };
  },
});

const HomeComponents = () => {
  const navigation = useRouter();
  const [response, setResponse] = useState({});

  useEffect(() => {
    const notificationOpenedAppListener = messaging().onNotificationOpenedApp(
      (remoteMessage) => {
        const screenType = remoteMessage?.data?.type;
        const chatId = remoteMessage?.data?.chat_id;
        const groupReplyId = remoteMessage?.data?.group_reply_id;

        if (screenType === "personal_chat" && chatId) {
          navigation.navigate(`/homescreen/chats/personalchat/${chatId}`);
        } else if (screenType === "group_reply" && groupReplyId) {
          navigation.navigate({
            pathname: "/homescreen/chats/groups/replayshow",
            params: { id: groupReplyId },
          });
        }
      }
    );

    const getInitialNotificationListener = messaging()
      .getInitialNotification()
      .then((remoteMessage) => {
        if (remoteMessage) {
          const screenType = remoteMessage?.data?.type;
          const chatId = remoteMessage?.data?.chat_id;
          const groupReplyId = remoteMessage?.data?.group_reply_id;

          if (screenType === "personal_chat" && chatId) {
            navigation.navigate(`/homescreen/chats/personalchat/${chatId}`);
          } else if (screenType === "group_reply" && groupReplyId) {
            navigation.navigate({
              pathname: "/homescreen/chats/groups/replayshow",
              params: { id: groupReplyId },
            });
          }
        }
      });

    const setBackgroundMessageHandlerListener = messaging().setBackgroundMessageHandler(async (remoteMessage) => {
      setResponse(remoteMessage);
      const chatId = remoteMessage.data.chat_id;
      const screenType = remoteMessage.data.type;
      const groupReplyId = remoteMessage?.data?.group_reply_id;

      if (screenType === "personal_chat" && chatId) {
        navigation.navigate(`/homescreen/chats/personalchat/${chatId}`);
      }
      if (screenType === "comment") {
        navigation.navigate(`/homescreen/post`);
      }
      if (screenType === "group_reply" && groupReplyId) {
        navigation.navigate({
          pathname: "/homescreen/chats/groups/replayshow",
          params: { id: groupReplyId },
        });
      }

      // Manually trigger a local notification
      await Notifications.scheduleNotificationAsync({
        content: {
          title: remoteMessage.notification.title,
          body: remoteMessage.notification.body,
          data: remoteMessage.data,
        },
        trigger: null, // Show immediately
      });
    });

    const onMessageListener = messaging().onMessage(async (remoteMessage) => {
      try {
        setResponse(remoteMessage);
        // Schedule notification to display
        await Notifications.scheduleNotificationAsync({
          content: {
            title: remoteMessage.notification.title,
            body: remoteMessage.notification.body,
            data: remoteMessage.data,
          },
          trigger: null, // Show immediately
        });
      } catch (error) {
        console.error("Error:", error);
      }
    });

    // Handle notification clicks
    const notificationResponseReceivedListener =
      Notifications.addNotificationResponseReceivedListener(() => {
        try {
          console.log(response);
          const screenType = response?.data?.type;
          const chatId = response?.data?.chat_id;
          const postId = response?.data?.post_id;
          const groupReplyId = response?.data?.group_reply_id;

          if (screenType === "personal_chat" && chatId) {
            navigation.navigate(`/homescreen/chats/personalchat/${chatId}`);
          }
          if (screenType === "comment" && postId) {
            navigation.navigate(`/homescreen/post/${postId}`);
          }
          if (screenType === "group_reply" && groupReplyId) {
            navigation.navigate({
              pathname: "/homescreen/chats/groups/replayshow",
              params: { id: groupReplyId },
            });
          }
        } catch (error) {
          console.error("Notification click error:", error);
        }
      });

    return () => {
      notificationOpenedAppListener();
      onMessageListener();
    };
  }, [navigation, response]);

  return <></>;
};

export default HomeComponents;

Issues:

  1. When the app is in a killed state and a new message arrives, clicking on the notification doesn’t open the app.

  2. When clicking on the notification, I’m getting the error: “No task registered for key ReactNativeFirebaseMessagingHeadlessTask”.

Could someone please guide me on how to resolve these issues?

Redirect keyword search result to a url

I am learning website building, html, css, javascript. I want to know how to redirect a search result to a url on click event.
I have a simple local website, not online, just on my pc.
I have few pages on it, with some kind of instructions on each page.
There is no back end, or server or database connected. So search only looks at avaialbe hard coded keywords in js file.

I built a search bar with autocomplete.
When I start typing in search box, possible matches show up in result box.

search result box

Results are coming from hard coded keywords in javascript file:

let availableKeywords = [
    'how to learn cooking',
    'hot to filter water',
    'how to make a soup',
    'how to use a mixer',
    'how to make flour',
    'how to write a recipe',
    'how to instal light bulb',
    'how to bake a cookie',
    'how to replace hard drive',
];

HTML Code for search box:

@*  Search bar area *@
<div class="search-box">
    <div class="row">
        <input type="text" id="input-box" placeholder="Search..." autocomplete="off" />
        <button type="submit"><i class="fa-solid fa-magnifying-glass"></i></button>
    </div>
   
    <div class="result-box">
        @*  this should be populated by script after searching keywords *@
    </div>
</div>

My JS function to check input box and match to keywords:

inputBox.onkeyup = function () {
    let result = [];
    let input = inputBox.value;
    /*if not zero or null*/
    if (input.length) {
        /* filter will match keywords defined above */
        result = availableKeywords.filter((keyword) => {
            return keyword.toLowerCase().includes(input.toLowerCase());
        });
        /* this is for debugging, it will be displayed in browser-console area */
        console.log(result);
    }
    /* show matches in results box */
    display(result);
    
    if (!result.length) {
        resultsBox.innerHTML = '';
    }
}

/* this will populate drop down box under search field if any matches */
function display(result) {
    const content = result.map((list) => {
        return "<li onclick=selectInput(this)>" + list + "</li>";
    });
    /* insert result list in html page */
    resultsBox.innerHTML = "<ul>" + content.join('') + "</ul>";
}

I would like to be able to redirect to a particular page/url when user clicks on one of the search results. For example if I click on “how to make soup”, I want the browser to go to //..makesoup.html

I do not know how to do that.
I suspect I need to create a map or dictionary that will map keywords to a url, something that should look like this (i guess):
The code below probably has wrong syntaxis, so my bad.

let keywordsWitUrl = [
    { 'how to learn cooking': "learnCooking.html"},
    { 'hot to filter water': "filterWater.html"},
    { 'how to make a soup': "makeSoup.html"},
    { 'how to use a mixer': "useMixer.html"},
    { 'how to make flour': "makeFlour.html"},
    { 'how to write a recipe': "writeRecipe.html"},
    { 'how to instal light bulb': "instalBulb.html"},
    { 'how to bake a cookie': "bakeCookie.html"},
    { 'how to replace hard drive': "replaceHD.html"}
];

I dont know how to do that in javascript and I can not find any help online..

How can I make my search to only search keywords and not associated urls ?
How can I bind keywords/full name of the instruction to a url?

I already have “on click” event, right now it just inserts the full name of instruction into the search box, and clears the result box.
How do I make page change to correct url when I click on some search result?

/* click event, display full article name and clear result box */
function selectInput(list) {
    inputBox.value = list.innerHTML;
    resultsBox.innerHTML = '';
}

I am not even sure where to start..
Any advice would help.
Thank you.

How to make many elements (div) wrap around one specific element (div) in html/css/js?

This is what I have right now:
my attempt

As you can see, the circles go under the big blue rectangle. But I want them to wrap around. I would look something like this:
implementation in paint3d

The rectangle has to be in the center. And notice the indexing, it would be good if it kept increasing from left-to-right, top-to-bottom

This is my code:

HTML

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script defer src="code.js"></script>
    <title>1440 Minutes wallpaper</title>
</head>
<body>
    <div id='flexbox'>
        <div id="info">big block</div>
        <div id="balls"></div>
    </div>
</body>
</html>

CSS

body {

    margin: 0px;
}
#flexbox {
    
    width: 2560px;
    height: 1440px;
}
#balls {

    width: 2520px;
    height: 960px;

    display: flex;
    flex-wrap: wrap;

}
#info {

    width: 560px;
    height: 440px;

    font-size: 50px;
    color: white;
    background-color: rgb(0,0,255,0.5);

    top: 500px;
    left: 1000px;

    position:absolute;
}
.MinuteBall {

    background-color: gray;

    width: 40px;
    height: 40px;
    margin: 1px;
    border-radius: 50%;
}

JS

document.body.onload = InitiateWallpaper;

function InitiateWallpaper() {

    for (let i = 0; i < 1440; i++) {

        const newDiv = document.createElement("div");
        newDiv.classList.add("MinuteBall");
        const text = document.createTextNode(i);
        newDiv.appendChild(text);

        const currentDiv = document.getElementById("balls");
        currentDiv.appendChild(newDiv);
    }
}

I am doing this thing only for myself, at least for now, so I am not interested and worried about supporting different screen sizes or browsers and stuff like that. Just Firefox and a 2560×1440 screen.

All the sizes that exist are experimental and don’t really matter as much as the wrap-around thing.

I am new to the web stuff and would appreciate your help a lot!

Should page redirection in AEM handled through javascript or anchor tag?

I have 4 button on homepage and upon clicking it I want to get redirected on another page.

I tried first something like this.

<a href="/content/travel/us/en/addticket.html" class="button-link">
<button class="add-ticket">
<span> ADD LEADS </span>
</button>
</a>

But it was not working.

Then I tried to do it using javascript and redirection was working.

Html

<button class="add-ticket">
<span> ADD LEADS </span>
</button>

Js

document.addEventListener('DOMContentLoaded', function(){
const addticketbutton =document.getElementById('add-ticket');
if(addticketbutton){
    addticketbutton.addEventListener('click', function(){
        window.location.href="/content/travel/us/en/addticket.html";
    });
});

What problem I’m facing with javascript is often i need to reload page or refresh. Sometimes redirection works sometimes not. Also achor tag gives us option to open in new tab.

I’m beginer in AEM and don’t know how to do this.

MediaRecorder HTML/JS sending to server

Hi I found the way to send the audio data to server by MediaRecorder, but it is works only as a recorder but I need a stream. I mean it works only after the stop of MediaRecorder. But I need to send data while it available, sort of audio stream…

My code:

mediaRecorderAudio.addEventListener("dataavailable", (stream) => {
    // Send stream data while mediaRecorderAudio is active
    ( async ()=>{
       let blob = new Blob(stream.data, { type: "audio/ogg; codecs=opus" });
       let buffer = await blob.arrayBuffer();
       let data_to_send =  new Uint8Array(buffer);
       socket.emit('socket_audio',JSON.stringify(data_to_send))
    });
});
mediaRecorderAudio.start(100);

If I starting and send to server just blobs, it is working while data availble. But with the coding of data to buffer – it not sends anything. I mean without async function. Any ideas?

HTML and JS PDF creation and sign with templates

I’m creating a new functionality for my medical management software. Others functionality are for examples appointments creation, invoices emissions and more. Now I’m focusing on creating a modules template to generate pdf and sign it. So doctors can create prescriptions and other stuff by writing the module just one time and use a “smart-tag” like ‘{patient-name}’ to avoid writing the patient or visit information every time and let my system substituting informations automatically. I actually already implemented a version of this, but in a more static way. Currently the pdf can have just one page without header and footer or with a header that have an image in the left and some text in the right and a footer with some text in the center. I want to extend this functionality with a more generic version. My clients need to add images in the body, make footer with 2 images or other things. For now I’m using a text area for all the text in header, body and footer and a file input to get the image for the header. I tried using a WYSIWYG editor and both pdfs library and html2canvas, but ended up having too many troubles because I can’t manage pages so when doctor are writing they can’t understand when a page is finished (I managed this by displaying a preview and updating while they write) and also I cannot understand where to place header and footer, the other solution is to make doctors copy and paste header and footer multiple times, but this became annoying and it’s not a great solution. Another problem is that when a module is created in a device with a certain monitor size and resolution, if you open the same module in another devices for example smaller it will create the PDF in a different way due to the size differences. Anyone can help? I’m searching for a more specific library to create PDF that manages pages and doesn’t cause me troubles with rendering the PDF on different devices. I’ve spent the last month searching for it, but the only ones that I’ve found similar are on paid options only and I really cannot afford it since they ask up to 3000$ per year. Even something about word documents would be great of course or google docs, but I did understand that integrating google docs would also not be free. Maybe the simplest way is to make them create the doc in word or google docs and that load the module in the software? I don’t really know what to do anymore.

I’m not sharing my code for now because the current solution must be destroyed and it’s far away form a good solution and the tries I did are all messed up and I did cancelled it all because I’m stuck with this problem in a while and it’s getting frustrating.

program for word and PDF files (open source or code tracking)

question

i want to create a program that can send commands into word or PDF files.
my question is does word and PDF have open source? that i can see the code?
another question that could eliminate the first one if possible is that my program sends commands to PDF file and then output a message to the user, so for example it tracks word count and then a pop up message shows up. now what i was woundering is if i start creating it, can my code still work on the PDF without needing to acces its source code? like tracking the PDF file word count and then the program print the message once it tracked it? if this is possible then my first question is no longer relevent, but if its not and i need acces to source code, then well let me know what are my options here. i asked chatgpt about it and it said its possible but sometimes its wrong, so a human response from a professional would help better.
thanks.

looking for

some guideness and suggestions