jsPDF not rendering tamil text properly - javascript

I am trying to generated invoice in tamil text using JSPDF with React-js. I have created a application which has print button and upon clicking it should generate PDF which I have described inside generateBill. I have added entire code in App.js file like below,
import React from 'react'
import { jsPDF } from "jspdf";
import {font} from './Lohit-Tamil-normal'
function App() {
function generateBill(event)
{
//Intializing jspdf
const doc = new jsPDF('p','mm',[200,80])
//Importing custom font for tamil
doc.addFileToVFS('Lohit-Tamil.ttf', font);
doc.addFont('Lohit-Tamil.ttf', 'Lohit-Tamil', 'normal')
doc.setFont('Lohit-Tamil');
//Adding text to pdf document
doc.text("பாத்திரக்கடை", 30,20);
//Calculating today date to display in PDF
let today = new Date();
let dd = String(today.getDate()).padStart(2, '0');
let mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
let yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
//Displaying today's date
doc.text(`தேதி: ${today}`, 5, 25, null, null, "left");
//Displaying customer name
doc.text(`வாடிக்கையாளர் பெயர்:`, 5, 30, null, null, "left");
//Setting tamil as language for PDF
doc.setLanguage("ta")
//saving the PDF file
doc.save('autoprint.pdf');
}
return (
<button type="button" onClick={generateBill}>Print</button>
</div>
);
}
Code inside imported font file - Lohit-Tamil-normal.js:
export const font = '[base64_encoded_text_of_ttf_file]';
But when I try to generated pdf, I am getting the text misplaced like below.
Actual pdf:
But what I expect to be like:
Few of the text like "டை,தே" are getting misplaced in front and back.
But when I tried to copy the text from PDF and paste it in my system, I am getting it proper. It will be great if anyone could shed some light and get this issue fixed.

jspdf is not compatible with few unicode script.
so either try with non unicode tamil fonts https://github.com/neechalkaran/neechalkaran.github.io/tree/master/tamilfonts/nonunicode
or
use pdfmake which has compatibility for Tamil https://pdfmake.github.io/docs/getting-started/

Related

How to put javascript variables from a form into a config file

I have a form (in Caspio Bridge) that the user fills out to create an event in a calendar. I'm using an 'Add to Calendar' module from an outside source (https://github.com/jekuer/add-to-calendar-button) to create a file for downloading to various calendars (google, ical, etc.).
In the Caspio form <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/add-to-calendar-button#1.8/assets/css/atcb.min.css"> and <script src="https://cdn.jsdelivr.net/npm/add-to-calendar-button#1.8" defer></script> are referenced to pull in the various files needed.
In the Caspio form a button click creates a config file that is used to create the download file and open the download options buttons.
I need to pull variables (event title, description, start date/time, end date/time) from the form, after the user enters data, and use those variables in creating the config file when the user clicks the Submit button. How is this done? Also, I can only alter the code shown here, not the referenced files.
Here are the javascript variables that get the user's input from the form:
var v_name = document.getElementById('InsertRecordTasksTimeline_Title').value;
var v_note = document.getElementById('InsertRecordTasksTimeline_Notes').value;
var v_location = document.getElementsByName('InsertRecordTasksTimeline_Location')[0].value;
Stamp = new Date(document.getElementById('InsertRecordTasksTimeline_CalDate').value);
Hours = Stamp.getHours()
Mins = Stamp.getMinutes();
v_BeginDate=('' + Stamp.getFullYear() +"-"+ (Stamp.getMonth()+1) + "-" + Stamp.getDate() +"T"+ Hours + ":" + Mins);
Stamp2 = new Date(document.getElementById('InsertRecordTasksTimeline_CalEnd').value);
Hours = Stamp2.getHours()
Mins = Stamp2.getMinutes();
v_EndDate=('' + Stamp2.getFullYear() +"-"+ (Stamp2.getMonth()+1) + "-" + Stamp2.getDate() +"T"+ Hours + ":" + Mins);
And here is the basic button that creates the config file: <button id="default-button" name="submitevent3">Submit</button>
Below is the code I have in the Caspio form that creates the config file, opens the download button options, and downloads a calendar file (.ics, etc). Note, for the values in this example there are just placeholders.
I somehow need to get the variables v_name, v_note, v_BeginDate, v_EndDate into the Config file so that name:v_name, description:v_note, startDate:v_BeginDate, endDate:v_EndDate. How would that be done?
const config = {
"name": "event title vale",
"description": "event note value",
"startDate" : "2022-06-01T10:15",
"endDate": "2022-06-01T12:30",
"location":"event location",
options: ["Google", "Apple","Microsoft365"],
timeZone: "currentBrowser",
trigger: "click",
iCalFileName: "Reminder-Event",
}
const button = document.querySelector('#default-button')
button.addEventListener('click', ()=> atcb_action(config, button)
)
I figured out the answer if anyone needs it. I have some code run onmouseover of a div with buttons in it. This code gets the variables and puts them in the config file. When one of the buttons is clicked it runs the config and the export options are available.
//*** SAVE Get variables and run EXPORT config**
document.querySelector("#divsave").addEventListener("mouseover", function getexport(){
const v_name = document.getElementById('InsertRecordTasksTimeline_Title').value;
const v_note = document.getElementById('InsertRecordTasksTimeline_Notes').value;
const v_proj = document.getElementsByName('cbParamVirtual11')[0].value;
const v_descrip = "Project: " + v_proj + "<br />" + v_note;
const sday = document.getElementById('cbParamVirtual15').value;
const eday = document.getElementById('cbParamVirtual10').value;
const stime = document.getElementById('timepicker').value;
const etime = document.getElementById('timepicker2').value;
const c_sday = new Date(sday).toLocaleDateString('fr-CA');
const c_eday = new Date(eday).toLocaleDateString('fr-CA');
const config = {
name: v_name,
description: v_descrip,
startDate: c_sday,
endDate: c_eday,
startTime: stime,
endTime: etime,
options: ["Apple",
"Google",
"iCal|ics file",
"Microsoft365",
"MicrosoftTeams",
"Outlook.com",],
timeZone: "currentBrowser",
trigger: "click",
iCalFileName: "Reminder-Event",
}
const button = document.querySelector('#default-button')
button.addEventListener('click', ()=> atcb_action(config, button)
)
});

How to have javascript presets today's date in HTML form

I am developing a project with Django.
I have an html webpage containing a form which has a date field.
I want javascript compile it with today's date as soon as my user lands on that webpage, so that he/she gets a kind of "default date".
I have in my html page (templates/aggiungi_terminologia.html), the date field:
<div class="form-group">
<label for="glossary_entry_input_21">Data di inserimento della terminologia</label>
<small id="inputHelp" class="form-text text-muted">Compilare solo se è nota la data di pubblicazione del documento fonte, altrimenti inserire la data di oggi.</small>
<input name="Data_inserimento_entry" type="date" value="01/01/1900" class="form-control" id="date_to_turn_into_today" placeholder="">
</div>
and then the javascript call at the end of the form:
{% load static %}
<script> src="{% static 'get_today_date.js' %}"</script>
And then, inside my javascript function (static/js/get_today_date.js):
var today = moment().format('DD/MM/YYYY');
document.getElementById("date_to_turn_into_today").value = today;
and since I am using moment.js, I added 'moment' in settings.py> INSTALLED_APPS ,
and to install moment I run on my console:
pip install django-staticfiles-moment
But when I run the server, all I get on that field is this:
My console is returning:
WARNINGS: app_glossario.glossary_entry.Data_inserimento_entry:
(fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to
have the current date as default, use django.utils.timezone.now
Why javascript is not replacing the date?
How can I make it work?
NOTE: the problem lies in the connection between js, html and django
Continue from comment about duplicated or not, take a look:
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day);
document.getElementById('inputDate').value = today;
<input type="date" id="inputDate" />
Please check this also.
I've seen similar behavior (where the input field shows a date placeholder instead of my desired date) when I provided a date string that was incorrectly formatted. The input element seems to need a format like yyyy-mm-dd.
Here's a pretty intuitive solution using vanilla JS. The default value of the input element will be the (locale-specific) date.
(And most of the further info you might want about JS Dates can be found here on MDN.)
const
// Selects input element
dateInput = document.getElementById("date"),
// Defines Date object
date = new Date(),
// Extracts component parts of Date object
year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
// Defines a function to add a leading zero if needed
pad = part => part < 10 ? "0" + part : part,
// Formats date to meet the `input` element's expectations -- like: `yyyy-mm-dd`
// (Adds +1 to month b/c `getMonth()` uses a zero-based array)
dateString = year + "-" + pad(month + 1) + "-" + pad(day);
// Inserts date string into input element
dateInput.defaultValue = dateString;
// Repeats this process for the "time" parts
/*
const
timeInput = document.getElementById("time"),
hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds(),
timeString = pad(hours) + ":" + pad(minutes) + ":" + pad(seconds);
timeInput.defaultValue = timeString;
*/
<input id="date" type="date" />
<!--
// Optional input for time
<input id="time" type="time" />
-->
SOLVED
Here is what I did.
In a javascript file called
get_today_date.js
stored at path
static/js/get_today_date.js
I inserted
function get_today_date() {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day);
document.getElementById('date_to_turn_into_today').value = today;
}
as suggested here https://stackoverflow.com/a/57953522/7658051 .
Then in the HTML page, before the closing </body> tag, I inserted
{% load static %}
<script type="text/javascript" src={% static "js/get_today_date.js" %}></script>
<script> get_today_date() </script>
and it works perfectly.
There was no neet to install the module moment, and even if my console returns
WARNINGS: app_glossario.glossary_entry.Data_inserimento_entry: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use django.utils.timezone.now
my app works fine.
The previous code did not work just because I forgot to call the function in HTML, so I just had to add
get_today_date()
But in the end I am not sure if I correctly installed the moment module required for the previuos javascript script.

javascript to update Joomla text field on page load

When a page loads, I need to add the current date in this format (mm/dd/yyy) into a Joomla form field using javascript. (the form extension does not have ability to do this) The field ID=938.
I tried using this code, but it is not working in Joomla so I assume there's a special code:
<script>
document.getElementById('938').value = (new Date()).format("mm/dd/yyyy");
</script>
Any help is appreciated.
JSN Uniform does not provide any option to display current date on field, so you can try following code.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10){
dd="0"+dd
}
if(mm<10){
mm="0"+mm
}
var today = mm+"/"+dd+"/"+yyyy;
document.getElementById('938').value = today;

JSON to CSV export works in Chrome, not in IE

My goal is to simply grab a JSON and export it as a CSV file. Ideally the user gets a prompt within the web browser that asks whether to save or open the CSV file.
I came across many examples that require a call to the server for the JSON to Excel/CSV conversion but I do need a JavaScript-only solution. I found this particular fiddle useful.
This works just fine when it's run with Chrome (v39) but nothing happens in IE11. In fact, I see a couple of errors in IE's console as follows:
I'm still trying to figure out whether these errors are browser specific, which I think they are. And if so, if there's any workaround. As my target browser is IE, "But it works in Chrome so use it" won't do me any good. I've spent hours trying to find a workaround for this to no avail, so any pointer in the right direction will be much appreciated.
Below is verbatim copy and paste of the aforementioned fiddle:
HTML
<div class='mydiv'>
<textarea id="txt" class='txtarea'>
[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road, West Bengal 734013, India","Speed":0},{"Vehicle":"Supra","Date":"30, Jul 2013 07:53 AM","Location":"Sec-45, St. Angel's School, Gurgaon, Haryana, India","Speed":58},{"Vehicle":"Land Cruiser","Date":"30, Jul 2013 09:35 AM","Location":"DLF Phase I, Marble Market, Gurgaon, Haryana, India","Speed":83},{"Vehicle":"Suzuki Swift","Date":"30, Jul 2013 12:02 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0},{"Vehicle":"Honda Civic","Date":"30, Jul 2013 12:00 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0},{"Vehicle":"Honda Accord","Date":"30, Jul 2013 11:05 AM","Location":"DLF Phase IV, Super Mart 1, Gurgaon, Haryana, India","Speed":71}]
</textarea>
<button class='gen_btn'>Generate File</button>
</div>
Script
$(document).ready(function(){
$('button').click(function(){
var data = $('#txt').val();
if(data == '')
return;
JSONToCSVConvertor(data, "Vehicle Report", true);
});
});
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//Set Report title in first row or line
CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
//Generate a file name
var fileName = "MyReport_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g,"_");
//Initialize file format you want csv or xls
var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
// Now the little tricky part.
// you can use either>> window.open(uri);
// but this will not work in some browsers
// or you will not get the correct file extension
//this trick will generate a temp <a /> tag
var link = document.createElement("a");
link.href = uri;
//set the visibility hidden so it will not effect on your web-layout
link.style = "visibility:hidden";
link.download = fileName + ".csv";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
IE normal doesnt support download tribute. you have to try with blob method.
conver the Json to CSV then usning blob you can download from IE.
nb : this wont work in IE9 or less will work in IE10+
https://stackoverflow.com/a/45641408/8151001
Are you hosting the jquery file or accessing it via a CDN? Try using Google's CDN.
https://developers.google.com/speed/libraries/devguide#jquery
Here is where the code is generating the error.
The problem is due to IE not supporting Data URIs to export CSV files:
https://msdn.microsoft.com/en-us/library/cc848897%28v=vs.85%29.aspx
The other browsers do. I know this is an old question. I hope you have found a work around in the past few months?

export javascript table to excel or to console table

I have build a table:
function insertTable(elementName, text, textColor, backgroundColor, relativeOffsetArea, fatherBC, scrollArea, offsetArea, clientArea) {
this.elementName = elementName;
this.text = text;
this.textColor = textColor;
this.backgroundColor = backgroundColor;
this.relativeOffsetArea = relativeOffsetArea;
this.fatherBC = fatherBC;
this.scrollArea = scrollArea;
this.offsetArea = offsetArea;
this.clientArea = clientArea;
}
And i'm adding to this table data during the running process..
but when I'm viewing the filled table in console log with this code:
console.table(consoleResult,["elementName", "text", "textColor", "backgroundColor", "relativeOffsetArea", "fatherBC", "scrollArea",
"offsetArea", "clientArea"]);
the maximum number of the lines is 1000.
does console table is limited to length of 1000 ?
Do you familiar with another way (maybe excel) to export this table ?
console.table only works in some browser versions. If you want this data in excel just loop it to a server script and download it as an xls with and html table in it. ( its a bit hacky but excel will happily open an html table saved as an xls file)
in php heres an example:
HTML table to excel - PHP

Categories

Resources