Creating an easy-to-update catalog utilizing an external file: A step-by-step guide

I am looking to create a product catalog with 1-4 products in a row, each displayed in a box with details and prices. I would like to be able to generate the catalog easily using an XML/CSV file that can be updated. Can anyone provide guidance on how to accomplish this? I have basic knowledge of HTML/CSS and can learn JavaScript if needed.

Once completed, the page will include a header followed by the products below. I plan to convert the page into a PDF for sharing with other users.

Answer №1

To start, it's essential to read your file and load it using JavaScript.

Once the file is loaded, you can then parse it into a JSON object.

Next step is to preview the content within an HTML table. (This HTML table will be used to create the PDF)

Using the library jsPDF and its plugin AutoTable, we create a PDF file with the previously generated HTML table.

Here is a sample CSV file that was used for testing:

Product,Price,Barcode
Sample product 1,100,802760000926
Sample product 2,95,802760000926
Sample product 3,20,802760000926

You can test it on my fiddle: https://jsfiddle.net/rogeliomonter/2f9m0qse/

let myList = {};
/*Function to load from CSV file*/
function openFile(event) {
    var input = event.target;
    var node = document.getElementById('output');
    node.innerText = '';
    var reader = new FileReader();
    reader.onload = function () {
        text = reader.result;
       //set to myList variable to be used later
        myList = JSON.parse(csvJSON(reader.result));
        buildHtmlTable('#output');
    };
    reader.readAsText(input.files[0]);
};

/*this function generates the HTML table*/
function buildHtmlTable(selector) {
    var columns = addAllColumnHeaders(myList, selector);

    for (var i = 0; i < myList.length; i++) {
        var row$ = $('<tr/>');
        for (var colIndex = 0; colIndex < columns.length; colIndex++) {
            var cellValue = myList[i][columns[colIndex]];
            if (cellValue == null) cellValue = "";
            row$.append($('<td/>').html(cellValue));
        }
        $(selector).append(row$);
    }
}

/*Supports the function that generates the HTML table*/
function addAllColumnHeaders(myList, selector) {
    var columnSet = [];
    var headerTr$ = $('<tr/>');

    for (var i = 0; i < myList.length; i++) {
        var rowHash = myList[i];
        for (var key in rowHash) {
            if ($.inArray(key, columnSet) == -1) {
                columnSet.push(key);
                headerTr$.append($('<th/>').html(key));
            }
        }
    }
    $(selector).append(headerTr$);

    return columnSet;
}

/*Converts CSV values into JSON object*/
function csvJSON(csv) {
    var lines = csv.split("\n");
    var result = [];
    var headers = lines[0].split(",");
    for (var i = 1; i < lines.length; i++) {

        var obj = {};
        var currentline = lines[i].split(",");
        for (var j = 0; j < headers.length; j++) {
            obj[headers[j]] = currentline[j];
        }
        result.push(obj);
    }
    //return result; //JavaScript object
    return JSON.stringify(result); //JSON
}

/*Uses jsPDF libary to generate a PDF File from the HTML table*/
function download() {
    // Default export is a4 paper, portrait, using millimeters for units
    const doc = new jsPDF();

    doc.text("My List", 10, 10);

    var columns = ["Product", "Price", "Barcode"];
    
    //Here we use the id of the table
    doc.autoTable({ html: '#output' })

    doc.save("myList.pdf");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.6/jspdf.plugin.autotable.min.js"></script>  
<input type='file' accept='text/csv' onchange='openFile(event)'>
  <br>
  <!-- the HTML table that will have the csv table -->
  <table id='output' border="1"></table>
  <br>
  <button onclick="download()">Generate PDF</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to use CSS to hyphenate a capitalized word?

I have a single word that needs to be hyphenated, but the lang=en hyphenate: auto property does not work on capitalized words. To address this, I utilized the slice function in JavaScript to split the word in half so that the second half, which requires h ...

Updating a column in a SQL Table via an Ajax request

I am attempting to store the on or off value from a form into an SQL database by calling a JS function with an AJAX request that sends it to a PHP page for processing. I seem to be facing some issues with my code and could really use some assistance as the ...

"Step-by-step guide for incorporating a mask in the Ant Design Datepicker component in React

Could someone help me figure out how to add a mask in the antd datepicker and validate it to ensure the correct date format (dd/mm/yy)? Here is the code I have attempted: <FormItem label="Date of Birth"> {getFieldDecorator("dob", {rules: [{ require ...

Error encountered: Attempting to render an object as a react component is invalid

I am attempting to query data from a Firestore database. My goal is to retrieve all the fields from the Missions collection that have the same ID as the field in Clients/1/Missions. Below, you can find the code for my query: However, when I tried to execu ...

"multer's single file upload functionality is not functioning properly, but the array upload

Currently, I am facing an issue while using react js to upload a single file. Interestingly, the multer.single() method seems to fail, whereas the multer.array() method works perfectly fine. What could be causing this problem? //Node.js const upload = mult ...

Preventing child element clicks in Angular 5: A helpful guide

I have checked numerous references, but unfortunately haven't received any responses. That's why I have turned to this platform in hopes of improving my code with your assistance. I need to add an element with text on click. Currently, it works ...

Utilize a custom function on dynamically generated elements

I am utilizing the following jQuery function: $("#agenda_image_1,#agenda_image_2,#agenda_image_3").PictureCut({ InputOfImageDirectory : "image", PluginFolderOnServer : "../xxx/modules/xxx/assets/js/jQuery-Picture-Cut-master/", Fol ...

How to Achieve an Overlapping Background Image Effect with Divs Using HTML and CSS

Is it possible to achieve the following scenario using just HTML and CSS? I want to display the background image of my HTML body through a clipped div. Keep in mind that the final website needs to be responsive (mobile-first), so any solution should accom ...

Error occurs when attempting to clear the cache storage

useEffect(async () => { caches.open('my-cache') }, [token, user_id]) Upon trying to log out of the application, const logoutFunc = () => { localStorage.clear() caches.keys().then((list) => list.map((key) => { ...

Developing numerous global objects within the context of JavaScript in Rails

I have an instance object called @cameras in my cameras controller's map method and am extracting necessary values from it for my specific purpose: + @cameras = load_user_cameras(true, false) + @map_data = [] + @cameras.each do |camera| + ...

Is it possible to trigger an event each time an Ajax request is made within AngularJS?

I am looking for a way to automatically display a spinner with a dark overlay every time a call is made to the backend. While I know I can manually implement this by triggering the spinner before each call, I prefer a solution that does not require addit ...

Enhance user experience with a flexbox navigation bar that dynamically adjusts link heights to ensure

I am struggling with making my navbar links the same height and keeping their text vertically centered, especially when they wrap onto multiple lines on a narrow viewport. While I have achieved vertical centering, I am facing difficulties in ensuring that ...

What steps can I take to resolve the issue of the "self signed certificate in certificate chain" error while trying to install plugins on VS Code?

After setting up VS Code on my Windows 7 x64 system, I encountered an issue when trying to install plugins - I kept receiving the error message "self signed certificate in certificate chain". Despite setting "http.proxyStrictSSL": false, I was still unable ...

In PHP, it is essential to always complete the necessary information in form validation

I've been working on implementing JavaScript form validation, but I seem to be having trouble with testing for empty fields in the form. Whenever I submit a fully filled out form, it keeps asking me to fill in the blank fields. Here is the code I hav ...

What is the most efficient method for appending /.json to the conclusion of express routes?

I am currently transitioning a DJANGO API to Node.js and have been tasked with ensuring that routes support the .json extension at the end. For instance, sending a GET request to /users/:id/.json should return a JSON object representing the user. The cha ...

The conditional statement in the given code snippet is failing to execute properly

const checkCondition = (props) => { let conditionMet = false; console.log('-----****----',props); if(props && props.isAllowed) { conditionMet = true; } if(someOtherCondition) { return( <li><Link className=" ...

Exploring Nested Objects in ReactJS

When I make a call to , I am able to access properties such as active_cryptocurrencies and active_markets, but for some reason, total_market_cap and total_volume_24h are returning as undefined. import React, { Component } from "react"; import { render } f ...

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...

Tips on transmitting form information from client-side JavaScript to server-side JavaScript with Node.js

Having created an HTML page with a form, my goal is to capture user input and store it in a JSON file. However, I've run into some confusion... In the process, I utilized the express module to set up a server. My mind is juggling concepts such as AJA ...

Having trouble retrieving data from the table with AJAX and CodeIgniter

I am currently developing a comprehensive HRM+CRM system (Human Resource Management and Customer Relation Management). I have encountered an issue while trying to generate an invoice for each customer. I am struggling to resolve this problem and would appr ...