112 lines
2.4 KiB
JavaScript
112 lines
2.4 KiB
JavaScript
|
/*
|
||
|
imagé({
|
||
|
input: "htmlcontent",
|
||
|
content: "<meta charset=\"UTF-8\"><h1 style='background-color:red;color:White'>This is a PDF</h1>",
|
||
|
generate: "pdf",
|
||
|
output: "json",
|
||
|
success: (data)=> {
|
||
|
console.log(data)
|
||
|
}
|
||
|
});
|
||
|
*/
|
||
|
async function imagé(options)
|
||
|
{
|
||
|
if(typeof options != "object")
|
||
|
{
|
||
|
throw new Error();
|
||
|
}
|
||
|
const {
|
||
|
input,
|
||
|
content,
|
||
|
endpoint,
|
||
|
generate,
|
||
|
output,
|
||
|
success,
|
||
|
...otheroptions
|
||
|
} = options;
|
||
|
|
||
|
let form = new FormData();
|
||
|
|
||
|
if(input == "htmlcontent")
|
||
|
{
|
||
|
if(typeof content != "string" || !content){
|
||
|
throw new Error();
|
||
|
};
|
||
|
|
||
|
form.append("content", content)
|
||
|
}
|
||
|
|
||
|
if(input == "endpoint")
|
||
|
{
|
||
|
if(typeof endpoint != "string" || !endpoint){
|
||
|
throw new Error();
|
||
|
};
|
||
|
|
||
|
form.append("endpoint", content)
|
||
|
}
|
||
|
|
||
|
if(generate != "pdf" && generate == "image")
|
||
|
{
|
||
|
throw new Error();
|
||
|
}
|
||
|
|
||
|
switch(output)
|
||
|
{
|
||
|
case "json":
|
||
|
case "json+base64":
|
||
|
case "content":{
|
||
|
form.append("output", output);
|
||
|
break;
|
||
|
};
|
||
|
default:{
|
||
|
throw new Error();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
for (const name in otheroptions) {
|
||
|
const value = otheroptions[name];
|
||
|
form.append(name, value);
|
||
|
}
|
||
|
|
||
|
let t = await fetch("http://localhost:8473/" + generate,{
|
||
|
method:"post",
|
||
|
body: form
|
||
|
});
|
||
|
|
||
|
if(!t.ok)
|
||
|
{
|
||
|
throw new Error();
|
||
|
}
|
||
|
|
||
|
if(
|
||
|
t.headers.get("content-type").indexOf("application/pdf") != -1 ||
|
||
|
t.headers.get("content-type").indexOf("image/png") != -1
|
||
|
)
|
||
|
{
|
||
|
let blob = await t.blob(), file;
|
||
|
if(generate == "pdf")
|
||
|
{
|
||
|
file = new File([blob],"File.pdf",{
|
||
|
lastModified: new Date(),
|
||
|
type:"application/pdf"
|
||
|
});
|
||
|
}else if(generate == "image"){
|
||
|
file = new File([blob],"File.png",{
|
||
|
lastModified: new Date(),
|
||
|
type:"image/png"
|
||
|
});
|
||
|
}
|
||
|
return (
|
||
|
typeof options.success == "function" &&
|
||
|
options.success(file),
|
||
|
file
|
||
|
);
|
||
|
}else{
|
||
|
let data = await t.json();
|
||
|
return (
|
||
|
typeof options.success == "function" &&
|
||
|
options.success(data),
|
||
|
data
|
||
|
);
|
||
|
}
|
||
|
}
|