Getting "PubSub Error Cannot read property 'widths' of undefined TypeError: Cannot read property 'widths' of undefined" - jspdf

I want to add custom font to jspdf document.
I am loading the file , converting it into base64 and then adding the font toVFS.
But I face the following error when I try to add the font and eventually the text to the pdf document.
PubSub Error No unicode cmap for font Error: No unicode cmap for font
Here is code:
getBase64 = (file)=>{
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
resolve(reader.result);
};
reader.onerror = error => reject(error);
});
};
downLoadPDF(){
console.log("download pdf");
let x= 10,y=40, page = 1;
var doc = new jsPDF("p", "mm", "a4");
doc.setFontSize(10);
doc.text("Page "+page++ , 185, 6);
var client = new XMLHttpRequest();
let inst = this;
client.open('GET', 'assets/fonts/Roboto-Bold.ttf');
client.onloadend = function() {
var fileData:any = client.responseText;
inst.getBase64(new Blob([fileData])).then((data:string)=>{
//Was getting "jsPDF PubSub Error Invalid string. Length must be a multiple of 4 Error: Invalid //string. Length must be a multiple of 4" error. So added the below line.
data = data + '='.repeat(4 - data.length % 4);
doc.addFileToVFS("Roboto-Bold.ttf",data);
doc.addFont("Roboto-Bold.ttf","Roboto-Bold","normal");
doc.setFont("Roboto-Bold","normal");
//Here, I get the following error:
//jsPDF PubSub Error No unicode cmap for font Error: No unicode cmap for font
//at i.registerTTF (jspdf.min.js:262)
//at new i (jspdf.min.js:262)
//at Function.i.open (jspdf.min.js:262)
//at Object.<anonymous> (jspdf.min.js:173)
//at oe.publish (jspdf.min.js:29)
//at Object.yt (jspdf.min.js:29)
//at Object.l.addFont (jspdf.min.js:29)
doc.text("Company Name: Avaya",x,y);y+=10;
});
}
client.send();
}

Related

TauriJS writeBinaryFile cannot freeze array buffer views with elements

I work with TauriJS and try to modify a zip file with jszip and later save it with writeBinaryFile.
function saveFile(org_path, new_path, pack_format) {
var zip = new JSZip();
// get file
var org_file = await window.__TAURI__.fs.readBinaryFile(org_path);
await zip.loadAsync(org_file);
// edit file
var pack_json = await zip.file("pack.json").async("string");
pack_json = JSON.parse(pack_json);
pack_json.pack.pack_format = pack_format;
zip.file("pack.json", JSON.stringify(pack_json));
// save file
var array_zip = await zip.generateAsync({type:"uint8array"});
await window.__TAURI__.fs.writeBinaryFile(new_path, array_zip);
}
This is the code I currently have. The problem is that it gives the error Uncaught TypeError: Cannot freeze array buffer views with elements
I wasn't able to find a solution to this error, is it somehow possible to bring the zip file in the right format to save it?
I found a way to fix the problem on this page:
https://qdmana.com/2022/144/202205241127535226.html
This is my adjusted code:
function saveFile(org_path, new_path, pack_format) {
var zip = new JSZip();
// get file
var org_file = await window.__TAURI__.fs.readBinaryFile(org_path);
await zip.loadAsync(org_file);
// edit file
var pack_json = await zip.file("pack.json").async("string");
pack_json = JSON.parse(pack_json);
pack_json.pack.pack_format = pack_format;
zip.file("pack.json", JSON.stringify(pack_json));
// save file
zip.generateAsync({ type: 'blob' }).then((content) => {
var file = new FileReader();
file.readAsArrayBuffer(content);
file.onload = function (e) {
var fileU8A = new Uint8Array(e.target.result);
window.__TAURI__.fs.writeBinaryFile({ contents: fileU8A, path: new_path + ".zip" });
};
});
}

Can't send readable stream with Pinata SDK to IPFS - 400 bad request and Unhandled rejection

Due to the nature of my project I have a image dataURL (NOT an actual image file) that I am trying to upload to IPFS via Pinata SDK. I have converted the image dataURL into a buffer(array) and tried 2 different methods but none of them works. Here is my code:
SAMPLE 1
var myBlob = new Blob([new Uint8Array(myBuffer)]);
var myReadableStream = myBlob.stream()
pinata.pinFileToIPFS(myReadableStream)
ERROR: Unhandled Rejection (TypeError): source.on is not a function
SAMPLE 2
var myBlob = new Blob([new Uint8Array(myBuffer)]);
var myHeaders = new Headers();
myHeaders.append("pinata_api_key", "MY_KEY");
myHeaders.append("pinata_secret_api_key", "MY_SECRET_KEY");
var formdata = new FormData();
formdata.append("test", myBlob);
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("https://api.pinata.cloud/pinning/pinFileToIPFS", requestOptions)
.then(response => response.text())
.then(result => console.log('result',result))
.catch(error => console.log('error', error));
ERROR: 400 Bad Request, result {"error":"Unexpected field"}
with buffers things can be a little tricky. You'll need to format your request in a slightly different way.
I would take a look at this code snippet for an example of how somebody got this to work:
const pinataSDK = require("#pinata/sdk");
const pinata = pinataSDK(
"Pinata API Key",
"Pinata API Secret"
);
const { fs, vol } = require("memfs");
(async () => {
try {
const base64 = "base64 file string";
const buf = Buffer.from(base64, "base64");
memfs.writeFileSync("File Name", buf);
const read = vol.createReadStream("File Name");
const res = await pinata.pinFileToIPFS(read);
console.log(res);
} catch (error) {
console.log(error);
}
})();

Unable to generate excel file from XLSX in ionic

I am creating excel file from user data but unfortunately its not generating file and even don't know what is the error so I can at-least try to solve that error.
Specially this issue occur in iOS platform only.
Please find below code to generate excel file:
public createXSLX(): Promise<any> {
return new Promise((resolve) => {
let sheet = XLSX.utils.json_to_sheet(this.data);
let wb = {
SheetNames: ["export"],
Sheets: {
"export": sheet
}
};
let wbout = XLSX.write(wb, {
bookType: 'xlsx',
bookSST: false,
type: 'binary'
});
function s2ab(s) {
let buf = new ArrayBuffer(s.length);
let view = new Uint8Array(buf);
for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
let blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
resolve(blob);
});
}
This above function works very well in android but in iOS its not generation file from provided data.
How I call above function code :
onExportNew = function (toEmail) {
this.createXSLX().then((xclBlob) => {
let time = new Date().getTime();
let fileName: string = "roster_" + time + ".xlsx";
var fs = ''
if (this.platform.is('ios')){
fs = this.file.documentsDirectory;
}else{
fs = this.file.externalDataDirectory;
}
console.log("File Path:- ",fs)
this.file.writeFile(fs, fileName, xclBlob, true).then(() => {
let fp = fs + fileName;
let email = {
// to: 'lmahajan#cisco.com',
// cc: 'erika#mustermann.de',
// bcc: ['john#doe.com', 'jane#doe.com'],
to: toEmail,
attachments: [fp],
subject: 'Roster Excel File',
body: '<h1>PFA</h1>',
isHtml: true
};
this.emailComposer.open(email).then(() => {
this.showDone = true;
}).catch(() => {
let toast = this.toastCtrl.create({
message: 'Could not open email composer',
duration: 3000
});
toast.present();
});
}).catch(() => {
this.displayAlert('Error', 'error creating file at: ' + fs);
});
}).catch(() => {
console.log("Excel file creation error");
});
}
Guide me if missing anything in above code.
Thanks in advance!

PDFJS and PDF encoding

We are implementing PDFJS to render pdf files on a website.
When trying to initiate a PDFdocument/Viewer as an arrayBuffer, we get al sorts of errors and the file is not rendered.
When opening the same file in the viewer from url (DEFAULT_URL variable), the file renders fine.
There are however some files that do render as streams. Comparing these files in notepad shows they have different encoding/characters.
This piece of code is used to open the file in the viewer:
function rawStringToBuffer( str ) {
var idx, len = str.length, arr = new Array( len );
for ( idx = 0 ; idx < len ; ++idx ) {
arr[ idx ] = str.charCodeAt(idx) & 0xFF;
}
return new Uint8Array( arr ).buffer;
}
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
var uint8array = rawStringToBuffer(contents);
pdfjsframe.contentWindow.PDFViewerApplication.open(uint8array,0);
};
reader.readAsText(file);
}
test.pdf helloworld pdf which is not rendered with code above.
test2.pdf helloworld pdf which does rendered with code above.
The behaviour is not browser dependent. The build is b15f335.
Is there something with the code or default configuration of the viewer so that test.pdf can not be rendered by the viewer?
I don't think that your string conversion routine rawStringToBuffer() does what you want. You are reading the file as text, which transforms UTF-8 to UTF-16. But rawStringToBuffer() just takes the low order byte of each UTF-16 character and discards the high order byte, which is not the inverse transform. This will work with 7-bit ASCII data, but not with other characters. The best way to convert a string to UTF-8 is with the TextEncoder API (not supported on all browsers but polyfills are available).
However, converting the data from UTF-8 and back again is unnecessary. Just use FileReader.readAsArrayBuffer() instead of readAsText() to produce your ArrayBuffer directly.
Here's an (untested) replacement function:
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
pdfjsframe.contentWindow.PDFViewerApplication.open(contents, 0);
};
reader.readAsArrayBuffer(file);
}

Using Dart to Download a PNG File (Binary File) and displaying it not working

I have a rest API which I am calling to retrieve a PNG image to display on my page.
My Code:
void getProfilePicture(var pic_id) {
request = new HttpRequest();
request.responseType = "blob";
request.onReadyStateChange.listen(onPicture);
// Get Basic Auth credentials
var authorization = 'Basic '+storage.loginData['password'];
// Build JSON
Map reqData = new Map();
reqData['id'] = pic_id.toString();
reqData['type'] = 'WEB_SMALL';
// SEND the request to the server.
var url = sifted.serverAPI+'/api/v1/pictures/getpicture';
request.open('POST', url);
request.withCredentials = false;
request.setRequestHeader('Authorization',authorization);
request.setRequestHeader('Content-Type','application/json');
request.send(json.stringify(reqData));
}
void onPicture(_) {
if (request.readyState == HttpRequest.DONE &&
request.status == 200) {
Blob blob = new Blob(request.response);
FileReader reader = new FileReader();
reader.onLoad.listen((fe) {
ImageElement imgInput = query('#profilepic');
imgInput.src = reader.result;
});
reader.readAsDataUrl(blob);
}
}
It does not work and I get these errors in the Dart editor:
Exception: type 'Blob' is not a subtype of type 'List' of 'blobParts'.
Exception: type 'Blob' is not a subtype of type 'List' of 'blobParts'.
Any suggestions on what I am doing wrong?
Thank you !
The problem is this line:
Blob blob = new Blob(request.response);
The Blob constructor expects a List instead of another Blob (which request.response is in your use case): factory Blob(List blobParts, [String type, String endings])
Just delete the line, and directly call reader.readAsDataUrl(request.response), and it should work.

Resources