I'm trying to generate some content for an HTML source dynamically, and then convert it to an Image (JPG or PNG) for later conversion into Base64.
For prefilling the HTML I'm using VelocityJS. And then attempting to use html-to-image library to convert the formatted HTML String/Element to an Image.
But I keep getting the following error.
oops, something went wrong! TypeError: Cannot read properties of undefined (reading 'defaultView')
at px (util.ts:69:1)
at getNodeWidth (util.ts:75:1)
at getImageSize (util.ts:87:1)
at toCanvas (index.ts:32:1)
at Module.toJpeg (index.ts:83:1)
at usePaymentReceiptBuilder.js:26:1
I first tried passing the string itself to the library. Which didn't work either. Then attempted adding the string into a div, and then wrapping it with JQuery to create an element. None of these worked.
The code is as follows.
import velocityjs from 'velocityjs';
import * as htmlToImage from 'html-to-image';
import paymentReceiptHtml from '../resources/email-receipts/payment-receipt.txt';
import useBusinessInfo from "./useBusinessInfo";
import $ from 'jquery';
const usePaymentReceiptBuilder = () => {
const {businessId, businessInfo, currencySymbol} = useBusinessInfo();
const PAPER_SIZE_TWO_INCH = 384;
const printReceiptOnCloverDevice = (purchaseEntry) => {
fetch(paymentReceiptHtml)
.then((response) => response.text())
.then((paymentReceiptHtmlTextContent) => {
let receiptContent = buildReceiptContent(purchaseEntry);
let velocityContext = {
"receiptContent": receiptContent
};
let renderedString = velocityjs.render(paymentReceiptHtmlTextContent, velocityContext);
// let htmlContent = <div dangerouslySetInnerHTML={{__html: renderedString}}/>;
let htmlContent = $(renderedString)
htmlToImage.toJpeg(htmlContent)
.then(function (dataUrl) {
console.log("generateReceiptBase64String 4");
console.log(dataUrl);
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
});
});
}
const buildReceiptContent = (purchaseEntry) => {
return {
businessName: businessInfo.businessName,
businessAddress: businessInfo.address,
businessWebsite: "",
businessContactNumber: businessInfo.contactNumbers.length > 1 ? businessInfo.contactNumbers[0] : "",
businessLogoUrl: "",
receiptOrderContent: purchaseEntry,
instanceMarketingUrl: "",
orderQrCodeBase64: "",
paperWidth: PAPER_SIZE_TWO_INCH
};
}
return {printReceiptOnCloverDevice}
}
export default usePaymentReceiptBuilder
What am I doing wrong? Please assist.