jsPDF not support a Thai language - javascript

I am using JsPDF for my Vuejs project and facing some issues while saving pdf for Thai version but it is working fine with English version.
Issues it is printing random special chracters
Any help would be appreciated.
Here is my code
exportTable () {
const pdf = jsPDF({
encoding: 'UTF-8',
defaultStyle: {
font: 'THSarabunNew'
}
});
pdf.addFileToVFS('THSarabunNew.ttf', THSarabunNew);
pdf.addFont('THSarabunNew.ttf', 'THSarabunNew');
pdf.setFont('THSarabunNew');
pdf.text('รายการสมรรถภาพทั้งหมด:', 14, 22);
this.data.forEach((item, index) => {
pdf.text(`Capacity Name : ${item.CapacityName}`, 14, 28 + (index * 10));
});
here is my problem

Related

How to generate ICS file for different calender's dynamically in reactJS

I have event data and I want user to be able to download ICS file and save it in calender of his choice
This is the function I am using but the ics file generated is only supported in outlook calender. How can I generate dynamic ICS file for all calneder type
export const saveCallInvite = (event) => {
const newEvent = { ...event, address: event?.event_url ? event?.event_url : `${event?.address?.line_1} ${event?.address?.line_2}, ${event?.address?.city} ${event?.address?.state}, ${event?.address?.country} ${event?.address?.postal_code} ` }
// Create the .ics URL
let url = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"BEGIN:VEVENT",
"DTSTART:" + newEvent.date,
"DTEND:",
"SUMMARY:" + newEvent.name,
"DESCRIPTION:" + newEvent.description,
"LOCATION:" + newEvent.address,
"BEGIN:VALARM",
"TRIGGER:-PT15M",
"REPEAT:1",
"DURATION:PT15M",
"ACTION:DISPLAY",
"DESCRIPTION:Reminder",
"END:VALARM",
"END:VEVENT",
"END:VCALENDAR"
].join("\n");
let blob = new Blob([url], { type: 'text/calendar;charset=utf-8' });
if (/msie\s|trident\/|edge\//i.test(window.navigator.userAgent)) {
// Open/Save link in IE and Edge
window.navigator.msSaveBlob(blob, `.ics`);
} else {
// Open/Save link in Modern Browsers
window.open(encodeURI("data:text/calendar;charset=utf8," + url));
}
}
Check that you have the minimum requirements for a valid ics file according to RFC5545. I see you are at least missing some VCALENDAR minimum requirements. Some calendar applications are more fussy than others, so it is best if the file is as valid as possible. See https://stackoverflow.com/a/67698638/440290
Then check your output ics file with all the ics validators. They do not all check everything and so may give you different errors and warnings.

Chinese character printed not corrected in SourceHanSansSC-Medium.otf

Description:
I've encountered a problem that a chinese character (胸) displays normally in html with 'SourceHanSansSC-Medium.otf' font but printed in a quite strange position while the html is printed by pdf reactor service.
If i replace it with SourceHanSansSC-Norml.otf, then both the html preview and the generated pdf by pdf-reacor are going well, only the SourceHanSansSC-Medium.otf useage will lead to this issue.
My environment :
System: Mac os 10.12.6, Java 8 Pdf reactor version: 10.0.
Preparation:
I pulled the pdf reactor image from docker hub and run it as a local docker container, that my app could visit it by http://localhost:9423/service/rest.
I write an very simple html contains the the error character in both SourceHanSansSC-Medium.otf and SourceHanSansSC-Medium.otf, just to compare the result of two fonts. They both display correctly in html preview, and only the medium font character would be printed in an incorrect position.
I mapped my html local parent path to pdf-reactor /ro/config to ensure the pdf-reactor is able to get the html to print.
HTML code:
This is My html code 'print_sc_font.html' (I attached the html the fonts in a zip):
<html>
<head>
<style type="text/css">
#font-face {
font-family: shssc-normal;
src: url("./SourceHanSansSC-Normal.otf");
}
#font-face {
font-family: shssc-medium;
src: url("./SourceHanSansSC-Medium.otf");
}
</style>
</head>
<body>
<div style="font-family: shssc-normal;">Print by SC Normal Font: 肺癌</div>
<div style="font-family: shssc-medium;">Print by SC Medium Font: 肺癌</div>
</body>
</html>
Html Preview is ok
Java Print Code (PdfReactorTest.java):
package com.gc.dev;
import com.realobjects.pdfreactor.webservice.client.Configuration;
import com.realobjects.pdfreactor.webservice.client.PDFreactor;
import com.realobjects.pdfreactor.webservice.client.PDFreactorWebserviceException;
import com.realobjects.pdfreactor.webservice.client.Result;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PDFReactorTest {
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String timeStamp = dateFormat.format(date);
// Create new PDFreactor instance
PDFreactor pdfReactor = new PDFreactor("http://localhost:9423/service/rest");
// Create a new configuration object
Configuration config = new Configuration()
// Specify the input document for Mac systems (adapt path if necessary) .setDocument("file:///ro/config/html/test/print_sc_font.html")
// Enable javaScriptSettings
.setJavaScriptMode(Configuration.JavaScriptMode.ENABLED)
// Set an appropriate log level
.setLogLevel(Configuration.LogLevel.DEBUG)
// Sets the title of the created PDF
.setTitle("Demonstration of PDFreactor Java API")
// Sets the author of the created PDF
.setAuthor("Myself")
// Enables links in the PDF document.
.setAddLinks(true)
// Enable bookmarks in the PDF document
.setAddBookmarks(true)
// Set some viewer preferences
.setViewerPreferences(
Configuration.ViewerPreferences.FIT_WINDOW,
Configuration.ViewerPreferences.PAGE_MODE_USE_THUMBS)
// Add user style sheets
.setUserStyleSheets(
new Configuration.Resource().setContent("#page {" +
"#top-center {" +
"content: 'PDFreactor Java API demonstration';" +
"}" +
" #bottom-center {" +
"content: \"Created on " + timeStamp + "\";" +
"}" +
"}"),
new Configuration.Resource().setUri("common.css"));
FileOutputStream fos = null;
try {
// Render document and save result to result
Result result = pdfReactor.convert(config);
if (result != null) {
byte[] pdf = result.getDocument();
//Save the pdf at the desired location
fos = new FileOutputStream("result.pdf");
fos.write(pdf);
fos.close();
}
} catch (PDFreactorWebserviceException exception) {
Result result = exception.getResult();
System.err.println(result.getError());
} catch (Exception e) {
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
}
}
Result pdf:
I haved attach my code and screen snapshot.
the SourceHanSansSC-Normal.otf is too large to attach, so two font files SourceHanSansSC-Normal and SourceHanSansSC-Medium.otf could be downloaded from https://github.com/adobe-fonts/source-han-sans/tree/release/OTF/SimplifiedChinese,
We can replicate this behavior using your fonts. This is a known issue, which is reported as #7530 in our internal tracker. The issue appears to be that the font subset containing certain characters is not embedded properly. As a workaround, you could make sure the entire font is embedded by adding the property "-ro-font-embedding-type: all;" to the "#font-face" rule declaration for this font, e.g.:
#font-face {
​font-family: shssc-medium;
-ro-font-embedding-type: all;
src: url("./SourceHanSansSC-Medium.otf");
}

Text alignment not appearing properly when generated PDF using .fromHTML method

I have created JavaScript code to get data from HTML back-end and convert that HTML into the PDF.
To generate PDF, I have used JSPDF.
My HTML string looks like below:
"<p><span style="font-family:calibri;font-size:17.3333px;">Dear [#Client Name],<br></span></p><p><span style="font-family:calibri;font-size:17.3333px;">This is a sample letter that I need filled out for [#Client Name 2], who lives in [#City],[#Province]. On this date, the [#Number Date], of ​[#Month],[#Year]. It occurred to me that [#Client Name] was talking to [#Client Name 3].<br></span></p><p><span style="font-family:calibri;font-size:17.3333px;">The end.</span></p><p><span style="font-family:calibri;font-size:17.3333px;">Appriciate your time.<br></span></p><p><span style="font-family:calibri;font-size:17.3333px;">[#Date]</span><br></p>"
The PDF which is generated using JSPDF looks like below:
The code to generate HTML is:
function GeneratePDF(content) {
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
doc.fromHTML(content, 15, 15, {
'width': 250,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
}
Can you please guide me how the alignment can be managed to manage the content. Also, how can I manage the font and how to remove þÿ character?
Please check
http://jsfiddle.net/2rhsvgkk/
Inspired by
How to properly use jsPDF library
HTML
<div id="customers">
<p>Dear [#Client Name],</p>
<p>This is a sample letter that I need filled out for [#Client Name 2], who lives in [#City], [#Province]. On this date, the [#Number Date], of [#Month],[#Year]. It occurred to me that [#Client Name] was talking to [#Client Name 3].</p>
<p>The end.</p>
<p>Appriciate your time.</p>
<p>[#Date]</p>
</div>
<button onclick="javascript:demoFromHTML();">PDF</button>
you are using some unnecessary <span> and <br> tags.
Hope this help you

How to include external JavaScript library in reactjs

I would like to know how it's possible to include an external JavaScript library in a react project. For example, I would like to import the jspdf library : https://github.com/MrRio/jsPDF/blob/master/jspdf.js and use it in my reactjs app.
So far I tried to use require like this : 
let React = require('react');
let { Spacing, Typography } = Styles;
let DoughnutChart = require("react-chartjs").Doughnut;
let Chart = require('react-google-charts').Chart;
let { StylePropable, StyleResizable } = Mixins;
let EditableDiv = require('../EditableDiv.jsx');
//some other library
//the library that matter for me
var pdfConverter = require('../utils/jspdf.source.js');
//then I have my classical react code which works and a function to generate ad pdf
_generatePdf: function(){
console.log('Genrating pdf');
var doc = new pdfConverter.jsPDF('p','pt');
var img = new Image();
}
I have the following error : TypeError: pdfConverter.jsPDF is not a function.
To make it work, I made something ugly, I copy the source of jspdf-source.js into my react.jsx file and just call jsPDF instead of pdfConverter.jsPDF. It's definitely no the right way, but can't succeed to import and use the library.
Can you tell me what I'm doing wrong and how I can correct this?
-EDIT-
When I was using my ugly solution (copying the source into my file) I just had to do the following :
var doc = new jsPDF('p','pt);
And it was working perfectly, expect that I had a very big file
After the suggested solution from #dannyjolie bellow, I've imported jspdf directly from the npm package, but I'm still not able to use the library. I tried the following code which lead to an error:
var pdfConverter = require('jspdf');
var converter = new pdfConverter();
var doc = converter.jsPDF('p', 'pt');
TypeError: pdfConverter is not a constructor
Meaning that I have to import the jsPDF coming from the package, not only jspdf?
Then I tried
let pdfConverter = require('jspdf');
var converter = pdfConverter.jsPDF;
var doc = new converter('p', 'pt');
ReferenceError: jsPDF is not defined
TypeError: converter is not a constructor
Ok, obviously, I'm not importing the right thing or not the right way.
What I'm doing wrong?
If you include the external js file link in your /public/index.html, you can use the external library with the window prefix.
Take JQuery as an example. Put the following line in your /public/index.html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Use it in your project like so:
window.$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
First of all, don't use the source file. Just npm install jspdf --save like any other package, and import it with var pdfConverter = require('jspdf');
Secondly, you're missing a () in this line var doc = new pdfConverter.jsPDF('p','pt');
Do something like this:
var converter = new pdfConverter();
var doc = converter.jsPDF('p', 'pt');
I know this is old, but I thought it would be helpful if someone posted a full working sample. It took me a while to figure this out, using this other post as a starting point:
How to make PDF from React?
Assuming you are using create-react-app, overwrite your App.js with the following below...
import React, { Component } from 'react';
import pdfConverter from 'jspdf';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.toDataUrl = this.toDataUrl.bind(this);
}
toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
onClick() {
var doc = new pdfConverter('p','pt','letter');
//console.log(doc.getFontList() );
this.toDataUrl('background.jpg', function(base64Img) {
var imgData = base64Img;
console.log(imgData);
console.log('Adding to doc.');
doc.addImage(imgData, 'JPEG', 0, 0, 612, 792);
console.log('Image added.');
doc.setFont('Times', 'Roman');
doc.setFontSize(22);
doc.text(20, 50, 'Park Entry Ticket');
doc.setFontSize(16);
doc.text(20, 80, 'Address1: ' );
doc.text(20, 100, 'Address2: ' );
doc.text(20, 120, 'Entry Date & time: ');
doc.text(20, 140, 'Expiry date & time: ' );
console.log('About to save');
doc.save("test.pdf");
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
<input type='button'
onClick={this.onClick} value="Print"/>
</p>
</div>
);
}
}
export default App;

Export data in CSV, Excel, PDF format in AngularJS

I want to add export table data in CSV, Excel, PDF format functionality in my app.
I am building app using angularjs 1.2.16.
Export data in Excel
I have used
<script src="https://rawgithub.com/eligrey/FileSaver.js/master/FileSaver.js" type="text/javascript"></script>
to export table to XLS format using following code :
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "report.xls");
above code is working fine.
Export data in CSV, PDF
In the same way i want to export data in CSV and PDF format.
I have used http://www.directiv.es/ng-csv to export data in CSV but it is not working fine in ubuntu libre office (file is showing corrupted data).
Can anyone tell me how to export table data in CSV,Excel and PDF format in angularjs?
You can export data from AngularJS to XLS, XLSX, CSV, and TAB formats with Alasql JavaScript library with XLSX.js.
Include two libraries into the code:
alasql.min.js
xlsx.core.min.js
To export data to Excel format create a function in the controller code:
function myCtrl($scope) {
$scope.exportData = function () {
alasql('SELECT * INTO XLSX("mydata.xlsx",{headers:true}) FROM ?',[$scope.items]);
};
$scope.items = [{a:1,b:10},{a:2,b:20},{a:3,b:30}];
};
Then create a button (or any other link) in HTML:
<div ng-controller="myCtrl">
<button ng-click="exportData()">Export</button>
</div>
Try this example in jsFiddle.
To save data into CSV format use CSV() function:
alasql("SELECT * INTO CSV('mydata.csv', {headers:true}) FROM ?",[$scope.mydata]);
Or use TXT(), CSV(), TAB(), XLS(), XLSX() functions for proper file formats.
If you're satisfied with a CSV file, then the ngCsv module is the way to go. You don't load elements from the DOM but export an array directly. Here you can see a sample of ngCsv in action.
The html:
<h2>Export {{sample}}</h2>
<div>
<button type="button" ng-csv="getArray" filename="test.csv">Export</button>
</div>
and the js:
angular.module('csv', ['ngCsv']);
function Main($scope) {
$scope.sample = "Sample";
$scope.getArray = [{a: 1, b:2}, {a:3, b:4}];
}
saveAs; To change the registered file extension, for example: "f:\folder\report.html" directory?
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8" });
saveAs(blob, "report.xls");
I've worked through several approaches and concluded the following, typesafe (DefinitelyTyped):
exportAsExcel(tableId: string, fileName: string, linkElement: any) {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
base64 = function (s) {
return window.btoa(decodeURI(encodeURIComponent(s)));
},
format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
});
};
// get the table data
var table = document.getElementById(tableId);
var ctx = {
worksheet: fileName,
table: table.innerHTML
};
// if browser is IE then save the file as blob, tested on IE10 and IE11
var browser = window.navigator.appVersion;
if ((browser.indexOf('Trident') !== -1 && browser.indexOf('rv:11') !== -1) ||
(browser.indexOf('MSIE 10') !== -1)) {
var builder = new MSBlobBuilder();
builder.append(uri + format(template, ctx));
var blob = builder.getBlob('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
window.navigator.msSaveBlob(blob, fileName + '.xlsx');
} else {
var element = document.getElementById(linkElement);
var a = document.createElement('a');
a.href = uri + base64(format(template, ctx));
a.target = '_blank';
a.setAttribute('download', fileName + '.xlsx');
document.body.appendChild(a);
a.click();
}
toastr.success("Awesome!", "We've created an Excel report for you and you should get it as a download in your browser.");
}
Kudos go to those who contributed of course in the various article.s
we can export data from a table into various format including
Json, Xml, Pdf .....
You can find detailed explanation http://www.prathapkudupublog.com/2015/10/angular-export-to-table.html
Note: This implementation would not run in IE
What do you need?
Angularjs
Jquery.js
Files referenced below
tableExport.js,JqueryBase64.js,html2canvas.js,base64.js,Jspdf.js,sprintf.js
<script type="text/javascript">
var myAppModule = angular.module('myApp', []);
myAppModule.controller('myCtrl', function ($scope) {
$scope.exportData = function () {
$('#customers').tableExport({ type: 'json', escape: 'false' });
};
$scope.items = [
{
"FirstName": "Prathap",
"LastName": "Kudupu",
"Address": "Near Anjana Beach"
},
{
"FirstName": "Deepak",
"LastName": "Dsouza",
"Address": "Near Nariman Point"
}
];
});

Categories