I have successfully got my static site to call a netlify function to access a pdf api keeping my tokens out of the page. Great.
The function looks like:
async function callApi2pdf(html,cName) {
const url = ‘/.netlify/functions/api2pdf’;
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (err) {
console.log(err);
}
}
My problem now is I want to actually pass the html of the page to the api for rendering as a pdf, along with one form field. I have tried changing the fetch method to post and accessing the event.body.xxxxx but this always produces json errors. For example:
const cname = JSON.parse(event.body.name) always throws an error.
Whats the best way of passing the data i need to the function? Ive been thru examples looking for something similar to this scenario but couldnt quite find somethng that obviously would fit the bill.
Hi @alanski ,
From the quick look I have had at the api2pdf documentation in the simplest for you perform at GET request https://v2018.api2pdf.com/chrome/url?url={UrlToConvert}&apikey={YourApiKey}
.
Have you tried capturing the URL of the page the function is called on (e.g. window.location.href
) instead of capturing the page body?
Thanks @coelmay. Because I’m changing the dom i want to send the endpoint the changed html rather than chrome option. Its working thru the netlify function just passing some static html (var =“
hello
”) but i need to get some of the form data from the page to the netlify function as well as the changed html/dom. So i thought I’d post the call to the netlify function but can’t read the post data in the function without error.
THanks @hrishikesh looks really useful
So I finally got my solution working with the help of this blog post here
I borrowed the method to use formData and passed this on the function ‘postFormDataAsJson’
Took me awhile to pick up the right sugar in the lambda function but got there in the end. I wasn’t sure i could pass a html page as json object thru lambda function but it works. Only taken me 16 hrs!
var fbody = JSON.parse(event.body)
var pname = fbody.name;
var pageHtml = fbody.pdfhtml;
const pdfName = 'My PDF doc for ' + pname;
const payload = {
"html": pageHtml,
"inlinePdf": false,
"fileName": pdfName,
"options": {
"marginBottom": 1.3
}
};
1 Like
Hey there, @alanski! Thank you so much for coming back and sharing your solution with us. This will most certainly help future Forums members who encounter something similar