javascript window print file locked after download

Inside a Reactjs version 16 i am using a call to window.print() native javascript function to generate a pdf file.

As a second step is necessary to select a PDF printer in the printer dialog window.

printScreen = () => {
    window.print();
  };



onClick={this.printScreen}

The PDF file gets locked after the download, and did not open for more or less five minutes.

i understand this is more a operational system problem than a javascript problem, as the message is Encountered a sharing violation while accessing (file path here….) .

Is there any other way, using javascript, to generate PDF files and allowing instant opening of the file ?

Any parameter accepted for window.print ?

Thank´s in advance

Reactpdf renderer not able register font

I am using React-PDF to generate PDFs in my React app, and I need to register multiple .ttf fonts. However, when I try to register them, I get the following error:

Error exporting PDF: Error: Unknown font format

I am registering fonts like this:


Font.register({
  family: "SF Pro Display",
  src: "/fonts/SF-Pro-Display-Regular.otf",
});

I have blocknote editor blocks just i wanna export as pdf when i was having tags like li or ol its started throwing err font is not register i have tried registering after that this err started coming tried some other npm to download as pdf this blockeditor is giving me a plain html with their classnames so i am not able see any colors and css styles in my pdf

Electron app crashes for users when msnodesqlv8 is required; Doesn’t crash locally

I have an electron app using ipc between the main process and renderer process. This is not a production build. Right now I’m just trying to do something simple: Display a SQL query on the page when the user presses a button. I’ve had this figured out for a while now, but for the love of me, I cannot figure out why this crashes when I try to distribute it to other users. I’ve tracked the issue down to msnodesqlv8, as everything works fine without it. When I require it in the global scope of main.js, the app crashes on startup. When its in the scope of the function called by the button’s onclick event, it crashes when the button is clicked. I’ve already ensured that they have access to the database, like I do. Here’s the function:

function executeQuery(connectionString, queryString) {
  const sql = require('msnodesqlv8');
  
  return new Promise((resolve, reject) => {
    sql.query(connectionString, queryString, (err, results) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(results);
    });
  });
}

And the function that calls it, both in main.js:

async function handleQuery() {

    const connectionString = "Driver={SQL Server};Server=<Server>;Database=<Database>;Trusted_Connection=Yes;TrustServerCertificate=Yes;";
    const query = "SELECT * from <Table> WHERE <Attribute> = <Value>";

    //Runs 
    let result = await executeQuery(connectionString, query);
    console.log(result)
    return result;

}

I am using Electron-Forge to make the app. Every time I try reinstalling msnodesqlb8, I make sure to rebuild it using .node_modules.binelectron-rebuild.cmd. Using npm list -g only outputs -- [email protected]
Again, when I make it and run Setup.exe locally, it works, and the page displays the result of the SQL query. When others run Setup.exe, it works until const sql = require('msnodesqlv8'); is reached, then crashes.

At the very least, is there a way to generate crash reports for my users so I can see what’s going on?

What’s the fastest and most efficient way of querying data from AWS DynamoDB

I’m building a sort of airbnb/booking.com clone where people can list their properties for rent. I have built the full domain with multiple tables referencing the center entity (which is property). This property entity is as followed:

id (Partition key) | title | description | hostId | createdAt | status | propertyType

Now I have multiple propertyTypes that I want to show seperately on different pages. So I made a Global Secondary Index on ‘status’ as ‘Partition key’ and ‘propertyType’ as ‘Sort key’ as I was told using the QueryCommand with a GSI is the quickest and most efficient way of getting filtered items. So I created a QueryCommand where the ‘status’ = “ACTIVE” and ‘propertyType’ = “Villa” with a ‘LIMIT’ of 20. I then map these values to retrieve some extra data from other tables. I do all this inside a Promise.all() which should mean that they run asynchronously and generally should be fairly quick. This is however not that case as I am something waiting for 3 seconds for only 3 results to return. I feel like I’m doing something wrong and the AWS DynamoDb documentation doesn’t really help me much further as I’ve built these queries off of their documentation.

In my service layer I call this function:

    async getPropertiesByType(type) {
        const propertyIdentifiers = await this.propertyRepository.getPropertiesByType(type);
        return await Promise.all(
            propertyIdentifiers.map(async (property) => {
                const [baseProperties, generalDetails, pricing, images] = await Promise.all([
                    this.getBasePropertyInfo(property),
                    this.getGeneralDetails(property),
                    this.getPricing(property),
                    this.getImages(property)
                ]);
                return {
                    property: baseProperties,
                    propertyGeneralDetails: generalDetails,
                    propertyPricing: pricing,
                    propertyImages: images
                };
            })
        );
    }

Which first calls this function:

    async getPropertiesByType(type) {
        const params = new QueryCommand({
            "TableName": await this.systemManager.getSystemManagerParameter("/dynamoDb/property-table"),
            "IndexName": "status-propertyType-index",
            "KeyConditionExpression": "#status = :status AND #propertyType = :propertyType",
            "ExpressionAttributeNames": {
                '#status': 'status',
                '#propertyType': 'propertyType'
            },
            "ExpressionAttributeValues": {
                ":status": {
                    "S": "ACTIVE"
                },
                ":propertyType": {
                    "S": type
                },
            },
            "Limit": 20
        });
        const result = await this.dynamoDbClient.send(params);
        if (result.Count < 1) {
            throw new NotFoundException(`No active property found for type ${type}.`)
        } else {
            const items = result.Items;
            return items.map(item => { return item.id.S});
        }
    }

Followed by these functions:

    async getBasePropertyInfo(property) {
        return await this.propertyRepository.getPropertyById(property);
    }

    async getGeneralDetails(property) {
        return await this.propertyGeneralDetailRepository.getPropertyGeneralDetailsByPropertyId(property);
    }

    async getPricing(property) {
        return await this.propertyPricingRepository.getPricingById(property);
    }

    async getImages(property) {
        return await this.propertyImageRepository.getImagesByPropertyId(property);
    }

Which call:

    async getPropertyById(id) {
        const params = new GetItemCommand({
            "TableName": await this.systemManager.getSystemManagerParameter("/dynamoDb/property-table"),
            "Key": { "id": { "S": id } }
        });
        const result = await this.dynamoDbClient.send(params);
        return result.Item ? PropertyBaseInfoMapping.mapDatabaseEntryToPropertyBaseInfo(result.Item) : null;
    }

    async getPropertyGeneralDetailsByPropertyId(id) {
        const params = new QueryCommand({
            "TableName": await this.systemManager.getSystemManagerParameter("/dynamoDb/property-general-detail-table"),
            "IndexName": "property_id-index",
            "KeyConditionExpression": "#property_id = :property_id",
            "ExpressionAttributeNames": {
                "#property_id": "property_id"
            },
            "ExpressionAttributeValues": {
                ":property_id": {
                    "S": id
                }
            }
        })
        const result = await this.dynamoDbClient.send(params);
        return result.Items ? result.Items.map(item => GeneralDetailMapping.mapDatabaseEntryToGeneralDetail(item)) : null;
    }

    async getPricingById(id) {
        const params = new GetItemCommand({
            "TableName": await this.systemManager.getSystemManagerParameter("/dynamoDb/property-pricing-table"),
            "Key": {
                "property_id": {
                    "S": id
                }
            }
        })
        const result = await this.dynamoDbClient.send(params);
        return result.Item ? PricingMapping.mapDatabaseEntryToPricing(result.Item) : null;
    }

    async getImagesByPropertyId(id) {
        const params = new QueryCommand({
            "TableName": await this.systemManager.getSystemManagerParameter("/dynamoDb/property-images-table"),
            "IndexName": "property_id-index",
            "KeyConditionExpression": "#property_id = :id",
            "ExpressionAttributeNames": {
                "#property_id": "property_id"
            },
            "ExpressionAttributeValues": {
                ":id": {
                    "S": id
                }
            }
        })
        const result = await this.dynamoDbClient.send(params);
        return result.Items ? result.Items.map(item => ImageMapping.mapDatabaseEntryToImage(item)) : null;
    }

Pass export through a main file in webpack

I am trying to build a library using webpack. When consuming my library, I want to be able to call myLibrary.showAlert() from a script tag or other js document. My issue is that I have multiple files all being imported into a main.js file which is the entry point of my library. If I import and export each file in main.js, it works. My question is, is there a way to export all files without listing each one individually?

Example:

//alerts.js
export function showAlert() {
  console.log("show alert called");
}

//translations.js
export function translateText() {
  console.log("translate text called");
}

//main.js
import "./components/alerts.js";
import "./components/translations.js";

     //Note: I want to avoid this part
export * from "/components/alerts.js";
export * from "/components/translations.js";

//webpack.library.config.js
const path = require("path");
const libraryName = "rmsui";
var configLib = Object.assign({}, config, {
    mode: "development",
    name: "myLibrary",
    entry: {
        // JS
        myLibrary: "./js/main.js",
        errorPages: "./js/errorPages.js" //some other entrypoint not shown above
    },
    output: {
        path: path.resolve(__dirname, "./wwwroot/dist"),
        filename: "js/[name].js",
        globalObject: "this",
        library: {
            name: libraryName,
            type: "umd",
        },
        libraryTarget: "var",
        //umdNamedDefine: true,
        assetModuleFilename: "assets/[hash][ext][query]"
    },
    plugins: [
        //new CleanWebpackPlugin(),
        new MiniCssExtractPlugin({
            filename: "css/[name].css"
        })
    ]
});
module.exports = configLib;

Self-parsing Markdown page with custom JavaScript

I have a self-parsing HTML page that utlizes markdown-it:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/markdown-it.min.js"></script>
<script src="markdown-it.js"></script>
<noscript>

**strong** and <mark>mark</mark>

<div style="background: #eee">

gray

</div>

</noscript>

markdown-it.js:

'use strict';

window.onload = function() {
  const markdown = document.querySelector('noscript').innerHTML;
  const md = window.markdownit({
    html: true, linkify: false, typographer: true
  });
  const html = md.render(markdown);
  document.querySelector('body').innerHTML = html;
}

It works.

Now, I want that page to show my browser and IP time zones.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/markdown-it.min.js"></script>
<script src="markdown-it.js"></script>
<noscript>

**strong** and <mark>mark</mark>

<div style="background: #eee">

gray

</div>

</noscript>

<p id="time-zones">&ZeroWidthSpace;</p>
<script src="js/time-zones.js"></script>

time-zones.js:

'use strict';

(async () => {
  const displayEl = document.querySelector("#time-zones");
  try {
    displayEl.textContent =
      Intl.DateTimeFormat().resolvedOptions().timeZone + " — " +
      (await (await fetch(`https://ipapi.co/json`)).json()).timezone;
  } catch ({message}) {
    displayEl.textContent = 'Error: ' + message;
  }
})();

But this doesn’t work. I mean, the time-zones.js code is correct, but there is some problem that prevents it to work on a Markdown page. How this can be fixed?

ReactJS: functions declared inside constants

In basically every piece of code I’ve seen in react projects, there are functions declared inside constants. It has come to a point where I use this kind of declaration without knowing why. For example, take this basic counter (javascript):

// ...
function App() {
  const [count, setCount] = useState(0);

  const handleClick = (e) => {
    e.preventDefault();
    setCount((prev) => (prev+1))
  }

  return (
    <div>
      {/* ... */}
      <button onClick={handleClick}>Increment</button>
      {/* ... */}
    </div>
  );
}
// ...

As you can see, handleClick is declared as a constant but has the value of a function. Why not declare it as a function right away like this (I’ve tested it and it works fine):

function handleClick(e) {
  e.preventDefault();
  setCount((prev) => prev + 1);
}

Is there a benefit in doing so? Is it just a javascript/typescript thing? Aren’t the two things the same?

Why is the text inside my Div Container not centered?

Question

Hey guys, I have a problem with aligning the text inside a div. Does anyone have an idea what is causing the problem? especially because it is already working on desktop chromium but not on any mobile device

Below I added two images that show the difference in the text alignment inside the div button__foreground__text. The Text on the mobile browsers is always way more up that the text on a desktop chromium browser.

HTML

<div className={scss["button__foreground"]}>
  <div className={scss["button__foreground__svg"]}>
    {props.children}
  </div>
  <div className={scss["button__foreground__text"]}>
    {props.text}
  </div>
</div>

CSS

.button__foreground {
  grid-area: row0 / col0 / row1 / col1;  

  display:flex;
  flex-wrap:wrap;
  align-items:center;
  justify-content:center;
  gap:lib.$stroke-width;

  height:100%;
}

.button__foreground__text {
  display:inline-block;
  line-height:1;
  border:black solid 1px;
  font-family:"Consolas";
  font-size:1rem;
  text-align:center;
  margin-top:auto;
  margin-bottom:auto;
}

.button__foreground__svg {
  display:grid;
  place-content:center;
  margin-top:auto;
  margin-bottom:auto;
}

This is how it looks on Safari on my phone, as you can see the text is not centered inside the div. I can observe the same behaviour on an android device using chrome.
Safari

But using a chromium based browser on my desktop on Windows, it works properly.
Chrome

Why I can’t use SockJsClient component from react-stomp library

While setting up WebSocket communication between SpringBoot backend and React.js + Vite frontend I ran into a problem at an import statement import SockJsClient from 'react-stomp';:

 "Could not find a declaration file for module 'react-stomp'. 'c:/Users/Mario/Desktop/kick-off/frontend/node_modules/react-stomp/dist/client.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/react-stomp` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-stomp';"

I’ve installed package via npm i sockjs react-stomp command which was added in dependencies in package.json

"sockjs": "^0.3.24"
"react-stomp": "^5.1.0"

I’ve tried the suggested npm i --save-dev @types/react-stomp and now I also see this:

npm error code E404
npm error 404 Not Found - GET https://registry.npmjs.org/@types%2freact-stomp - Not found
npm error 404
npm error 404  '@types/react-stomp@*' is not in this registry.
npm error 404
npm error 404 Note that you can also install from a
npm error 404 tarball, folder, http url, or git url.
npm error A complete log of this run can be found in: C:UsersMarioAppDataLocalnpm-cache_logs2025-03-20T16_02_27_649Z-debug-0.log

I have no idea what registry is and how to figure out something from the logs.
I’ve tried to search how to add to registry but it didn’t help.

Now I’m going to paste all of my code
App.jsx

import SockJsClient from 'react-stomp';


const SOCKET_URL = 'http://localhost:8080/ws-message';

function App() {
  const [message, setMessage] = useState('Your server message here.');

  let onConnected = () => {
    console.log("Connected!");
  }

  let onMessageReceived = (msg) => {
    setMessage(msg.message);
  }

  return(
    <div>
      <SockJsClient
        url={SOCKET_URL}
        topics={['/topic/message']}
        onConnected={onConnected}
        onDisconnected={console.log("Disconnected!")}
        onMessage={msg => onMessageReceived(msg)}
        debug={false}
      />
      <div className='text-white mt-40 ml-80'>{message}</div>



      </div>
  )
}
export default App;

SpringBoot config file

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws-message").setAllowedOriginPatterns("*").withSockJS();
    }
}

@RestController
public class WebSocketTextController {

    final SimpMessagingTemplate template;

    public WebSocketTextController(SimpMessagingTemplate simpMessagingTemplate) {
        this.template = simpMessagingTemplate;
    }

SpringBoot controller

    @PostMapping("/send")
    public ResponseEntity<TextMessageDto> sendMessage(@RequestBody TextMessageDto textMessageDto) {
        System.out.println("text message: " + textMessageDto);
        template.convertAndSend("/topic/message", textMessageDto);
        return new ResponseEntity<>(textMessageDto, HttpStatus.OK);
    }

    @MessageMapping("/sendMessage")
    public void receiveMessage(@Payload TextMessageDto textMessageDto) {
    }

    @SendTo("/topic/message")
    public TextMessageDto broadcastMessage(@Payload TextMessageDto textMessageDto) {
        return textMessageDto;
    }
}

Expected bahaviour
I used Postman to send an message to be displayed on the webapp but it doesn’t work.
What I do get in web console is message “Disconnected!”
enter image description here

Source https://umes4ever.medium.com/real-time-application-using-websocket-spring-boot-java-react-js-flutter-eb87fe95f94f – this is the tutorial I’m following.

Build a specific array [closed]

I want to build some array :

  • first : array1 = [1, 2, 3, ..., 31] (days of month for example march)
  • Second : array2 = ["mon.", "tue.", ..., "sun.] (name of the days)

all are push in an array_data like this :

data = [[1, 2, 3, ..., 31],["mon.", "tue.", ..., "sun.]]

I want to insert another array (inline) after array 2 like this :

data = [[1, 2, 3, ..., 31],["mon.", "tue.", ..., "sun.], ["name", "X", "", "", "", "", "X", ..., ""]]

I have an object to loop the “names” of agents and if they work in the day then insert “X” in the case of the day for this agent.

How can I except this?

Show different text in a separate div by select options

I’m trying to show different text when selecting an option from a select, but it doesn’t work.

I’m trying to get the open button to display text 1, then depending on the option chosen the text changes, and finally for the displayed text to disappear when pressing close.

I know the javascript code is long and bad, but please don’t judge me, it’s not easy for me. Thank you.

$(document).ready(function($){
$('#open').on('click', function(event){
    $('#Text1').addClass('visible');
});
});
$(document).ready(function($){
$('#close').on('click', function(event){
    $('#Text1').removeClass('visible');
    $('#Text2').removeClass('visible');
    $('#Text3').removeClass('visible');
    $('#Text4').removeClass('visible');
    $('#Text5').removeClass('visible');
});
});
$(document).ready(function($){
$("#select").val("1").on('change', function(event){
    $('#Text1').addClass('visible');
    $('#Text2').removeClass('visible');
    $('#Text3').removeClass('visible');
    $('#Text4').removeClass('visible');
    $('#Text5').removeClass('visible');
});
});
$(document).ready(function($){
$("#select").val("2").on('change', function(event){
    $('#Text1').removeClass('visible');
    $('#Text2').addClass('visible');
    $('#Text3').removeClass('visible');
    $('#Text4').removeClass('visible');
    $('#Text5').removeClass('visible');
});
});
$(document).ready(function($){
$("#select").val("3").on('change', function(event){
    $('#Text1').removeClass('visible');
    $('#Text2').removeClass('visible');
    $('#Text3').addClass('visible');
    $('#Text4').removeClass('visible');
    $('#Text5').removeClass('visible');
});
$(document).ready(function($){
$("#select").val("4").on('change', function(event){
    $('#Text1').removeClass('visible');
    $('#Text2').removeClass('visible');
    $('#Text3').removeClass('visible');
    $('#Text4').addClass('visible');
    $('#Text5').removeClass('visible');
});
});
$(document).ready(function($){
$("#select").val("5").on('change', function(event){
    $('#Text1').removeClass('visible');
    $('#Text2').removeClass('visible');
    $('#Text3').removeClass('visible');
    $('#Text4').removeClass('visible');
    $('#Text5').addClass('visible');
});
});

https://jsfiddle.net/ytgb3p27/10/