Using html-pdf with dynamic data - javascript

Currently I am testing html-pdf module to generate pdfs from html. And I have successfully generated one. But the issue is that the text/data in the html is fixed at the moment.
What I am trying to do is have an html form on the front-end which the user fills and then generate a pdf which includes the content the user typed.
What I have done so far:
app.post('/pdf',function(req, res) {
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res);
});
});
Is this possible using html-pdf? Any help will be greatly appreciated.

Unfortunately, html-pdf module can't handle the dynamic data. You can take a look at the phantomjs which does the screen capture.
In fact, html-pdf module uses "phantomjs" at background. However, it uses the small feature of phantomjs.

You can check dynamic-html-pdf
Just follow the steps:
Install using this command npm install dynamic-html-pdf --save
Create html template
Create pdf with below code:
var fs = require('fs');
var pdf = require('dynamic-html-pdf');
var html = fs.readFileSync('template.html', 'utf8');
pdf.registerHelper('ifCond', function (v1, v2, options) {
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
})
var options = {
format: "A3",
orientation: "portrait",
border: "10mm"
};
//Your dynamic data
var users = [
{
name: 'aaa',
age: 24,
dob: '1/1/1991'
},
{
name: 'bbb',
age: 25,
dob: '1/1/1995'
},
{
name: 'ccc',
age: 24,
dob: '1/1/1994'
}
];
var document = {
type: 'buffer', // 'file' or 'buffer'
template: html,
context: {
users: users
},
path: "./output.pdf" // it is not required if type is buffer
};
pdf.create(document, options)
.then(res => {
console.log(res)
})
.catch(error => {
console.error(error)
});

I was finding solution for the same and got around one.
https://medium.com/free-code-camp/how-to-generate-dynamic-pdfs-using-react-and-nodejs-eac9e9cb4dde
you can checkout this work around done in the blog.
He simply called a function that returns an HTML string and he use backticks for dynamic data.

Related

Sending data to service array brute force

I can't find an answer to my question, can you help me friends
what kind of requests, I get: facebook, linkedin, reddit
I don't want to write a lot of code, so I want to ask you how I can make
How do I create a check loop, and send the data (the data is the same for all services)
to go through and find the right service. send the right service and data. Again, the data for all services is the same
as you can see, I write a lot of conditional statements, and I don't like it, I want to put
I use ejs, express
I just want to get rid of a lot of code..
everything into one loop and work
var servies = ["facebook", "linkedin", "reddit"]
servies.forEach(service => {
console.log(service);
});
if (service == "linkedin") {
res.render('linkedin', {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
}
if (service == "reddit") {
res.render('reddit', {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
}
if (service == "facebook") {
res.render('facebook', {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
}
You can try
var servies = ["facebook", "linkedin", "reddit"]
servies.forEach(service => {
console.log(service);
res.render(service, {
id: xssFilters(id),
name: xssFilters(name),
image: xssFilters(photo),
firstName: xssFilters(firstName),
})
});
since in your example code, you don't do anything different between the different services, but only replace the string name of the service, and you already have a loop for that.

Filters in Power BI embed report

I developed a few months ago a NodeJS API to get embed reports from Power BI (using a tenant). I consume this API from an Angular app. Now I want to get the report filtered, and I don't know if this is possible with my actual code.
I used the PowerBI rest API to get the embed report. Reading the docs of microsoft, I see lots of docs like this one, where says that I should create an object with the filters that I want. This is not a problem, but I don't know if this is compatible with mi actual Node API or I should develop a new solution.
My API follows the sample provided by Microsoft, and the code is:
async function getEmbedParamsForSingleReport(
workspaceId,
reportId,
additionalDatasetId
) {
const reportInGroupApi = `https://api.powerbi.com/v1.0/myorg/groups/${workspaceId}/reports/${reportId}`;
const headers = await getRequestHeader();
// Get report info by calling the PowerBI REST API
const result = await axios.get(reportInGroupApi, { headers });
if (result.status !== 200) {
throw result;
}
// Convert result in json to retrieve values
const resultJson = result.data;
// Add report data for embedding
const reportDetails = new PowerBiReportDetails(
resultJson.id,
resultJson.name,
resultJson.embedUrl
);
const reportEmbedConfig = new EmbedConfig();
// Create mapping for report and Embed URL
reportEmbedConfig.reportsDetail = [reportDetails];
// Create list of datasets
let datasetIds = [resultJson.datasetId];
// Append additional dataset to the list to achieve dynamic binding later
if (additionalDatasetId) {
datasetIds.push(additionalDatasetId);
}
// Get Embed token multiple resources
reportEmbedConfig.embedToken =
await getEmbedTokenForSingleReportSingleWorkspace(
reportId,
datasetIds,
workspaceId
);
return reportEmbedConfig;
}
With this I obtain the embed report and send back to my app. Is this solution compatible with filters?
Thanks in advance!
Finally, I came out with a solution. In mi Angular app, I use the library powerbi-client-angular. That allows me to define some configuration in the embed report:
basicFilter: models.IBasicFilter = {
$schema: 'http://powerbi.com/product/schema#basic',
target: {
table: 'items',
column: 'id',
},
operator: 'In',
values: [1,2,3],
filterType: models.FilterType.Basic,
requireSingleSelection: true,
displaySettings: {
/** Hiding filter pane */
isLockedInViewMode: true,
isHiddenInViewMode: true,
},
};
reportConfig: IReportEmbedConfiguration = {
type: 'report',
id: cuantitativeReportID,
embedUrl: undefined,
tokenType: models.TokenType.Embed,
filters: [this.basicFilter],
accessToken: undefined,
settings: undefined,
};
With this, I can avoid passing information to the NodeJS API
Yes, It will work fine with this solution. Please find the relevant code below:
Create a filter object:
const filter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
table: "Geo",
column: "Region"
},
operator: "In",
values: ["West", "Central"]
};
Add the filter to the report's filters:
await report.updateFilters(models.FiltersOperations.Add, [filter]);
You can refer sample NodeJS application to get embed reports from Power BI.
Please find the the reference here:
https://github.com/microsoft/PowerBI-Developer-Samples/tree/master/NodeJS

Mapping data from Object of Objects in React

I am fetching some data from an api and I want to map through it inorder to get all the values inside . But I am unable to do so . Need some help.
Here's the data :
{
'id:5': {
1: {
coinid: 5,
coinname: 'Chainlink',
publishedAt: '2021-06-24T11:10:54Z',
source: 'Cointelegraph',
title:
'asset manager qr launches bitcoin etf on brazilian stock exchange',
description:
'in contrast to hashdexs crypto etf product qr asset managements product provides exposure to bitcoin exclusively',
url: 'https://cointelegraph.com/news/asset-manager-qr-launches-bitcoin-etf-on-brazilian-stock-exchange',
},
2: {
coinid: 5,
coinname: 'Chainlink',
publishedAt: '2021-06-24T13:39:56Z',
source: 'Business Wire',
title:
'truefi announces new integrations with binance chainlink and sushiswap further embedding into the defi ecosystem',
description:
'san franciscobusiness wire binancetrusttoken announces a suite of deep defi integrations designed to make the truefi platform safer more robust and more lucrative for its users',
url: 'https://www.businesswire.com/news/home/20210624005642/en/TrueFi-Announces-New-Integrations-With-Bina',
},
}
and here is my code for fetching api ( I have to unescape the api data coz it was in escaped form) :
const fetchNews = async () => {
try {
const { data } = await axios.get(
'https://h3iiccq04i.execute-api.ap-south-1.amazonaws.com/dev',
);
console.log(JSON.parse(data));
// setNewsData(JSON.parse(data));
setLoading(false);
} catch (err) {
console.log(err.message);
}
};
here the newsData is an object which I have to map and get all the values such as coinname ,url ,etc . Any help would be really appreciated .
We could use Object.values() to get in an array with all the object values and then iterate over it with a map.
const dataArray = Object.values(data['id:5'])
dataArray.map(...)

Razor Pay checkout form not appearing and giving error as not a function

I am implementing razorPay payment in angular7 project.I am trying to open checkout form by creating a single instance of Razorpay and accessing its function open(). But instead it is throwing error "is not a function". I couldn't find any proper documentation regarding this.
However, If I try to simple create payment using razorpay, it opens up the window but there is no option for user to choose any method and hence it throws error again because directly creating payment will not add up any card(if method is 'card'). So it is necessary to open checkout form.
Here is my function I am using, firstly i create order on server to generate id and then proceed to payment.
buyPlan() {
let postdata = {
amount: 1000,
currency: "INR",
receipt: "1",
notes: {},
payment_capture: true
}
this.common.createOrder(postdata).subscribe(
(result: any) => {
console.log(result)
var razorpay = new this.winRef.nativeWindow.Razorpay({
key: 'dashboard_key_id',
image: 'assets/images/logo-1.png',
});
var data = {
amount: 1000,
currency: "INR",
email: 'abc#example.com',
contact: '9874563210',
notes: {
address: 'Sector 65 Delhi',
},
method: 'card',
order_id: result.data.id,
handler: function (response) {
alert(response.razorpay_payment_id);
}
};
razorpay.open();
}, (err: HttpErrorResponse) => {
}
);
}
For Custom Integration
Remove:
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
from index.html file
and put:
<script type="text/javascript" src="https://checkout.razorpay.com/v1/razorpay.js"></script>
inside <head></head> tag

How can I retrieve,add data using Quickbase API and javascript

I am very new to Quickbase.
I want to query the quickbase using javascript to get a table records and also insert to it.
How should I do this?
Any help is highly appreciated.
To improve #rtpHarry's answer, the JavaScript SDK he is referencing has seen better days. It hasn't been updated in 2 years, and doesn't work in IE11.
Now this is a shameless plug, full disclosure, I am the author of this module;
But Node-QuickBase is much, much easier to use and works both in the browser and on the server - no code change.
Here is an example:
Within Nodejs:
var QuickBase = require('quickbase');
var quickbase = new QuickBase({
realm: 'www',
appToken: '*****'
});
quickbase.api('API_Authenticate', {
username: '*****',
password: '*****'
}).then(function(result){
return quickbase.api('API_DoQuery', {
dbid: '*****',
clist: '3.12',
options: 'num-5'
}).then(function(result){
return result.table.records;
});
}).map(function(record){
return quickbase.api('API_EditRecord', {
dbid: '*****',
rid: record[3],
fields: [
{ fid: 12, value: record[12] }
]
});
}).then(function(){
return quickbase.api('API_DoQuery', {
dbid: '*****',
clist: '3.12',
options: 'num-5'
});
}).then(function(result){
console.log(result);
}).catch(function(err){
console.error(err);
});
Within the Browser:
<script type="text/javascript" src="quickbase.browserify.min.js"></script>
<script type="text/javascript">
var quickbase = new QuickBase({
realm: 'www',
appToken: '*****'
});
quickbase.api('API_Authenticate', {
username: '*****',
password: '*****'
}).then(function(result){
return quickbase.api('API_DoQuery', {
dbid: '*****',
clist: '3.12',
options: 'num-5'
}).then(function(result){
return result.table.records;
});
}).map(function(record){
return quickbase.api('API_EditRecord', {
dbid: '*****',
rid: record[3],
fields: [
{ fid: 12, value: record[12] }
]
});
}).then(function(){
return quickbase.api('API_DoQuery', {
dbid: '*****',
clist: '3.12',
options: 'num-5'
});
}).then(function(result){
console.log(result);
}).catch(function(err){
console.error(err);
});
</script>
Before you begin you need to set up a user in QuickBase.
In order for you to use the API you need to have a developer key.
There is a JavaScript SDK that you can use which is available on GitHub. This will shield you from the details of the API.
However, this doesn't let you use this inside any random webpage if that's what you're attempting:
HTML pages using QuickBaseClient.js must be hosted within QuickBase
applications as file attachments or as text (code) pages because web
browsers only allow JavaScript code to access the web site the
JavaScript originated from.
If you do want do that then there are workarounds.

Categories

Resources