-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfiscor-pdf-api-example.js
More file actions
80 lines (65 loc) · 1.93 KB
/
Copy pathfiscor-pdf-api-example.js
File metadata and controls
80 lines (65 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const baseUrl = "https://pdf.fiscor.am/api/v1";
export async function convertPdfToWord({ apiKey, file }) {
const form = new FormData();
form.append("file", file, file.name);
const createResponse = await fetch(`${baseUrl}/jobs/pdf-to-word`, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
},
body: form,
});
const createBody = await createResponse.json();
if (!createResponse.ok) {
throw new Error(createBody.error ?? "Could not create conversion job.");
}
const jobId = createBody.jobId;
await waitForCompletion(apiKey, jobId);
const downloadResponse = await fetch(`${baseUrl}/jobs/${jobId}/download`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
if (!downloadResponse.ok) {
throw new Error("Could not download conversion result.");
}
return {
jobId,
blob: await downloadResponse.blob(),
};
}
async function waitForCompletion(apiKey, jobId) {
for (let attempt = 1; attempt <= 60; attempt++) {
const response = await fetch(`${baseUrl}/jobs/${jobId}`, {
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
const body = await response.json();
if (!response.ok) {
throw new Error(body.error ?? "Could not read job status.");
}
if (body.status === "Completed") {
return;
}
if (body.status === "Failed") {
throw new Error(body.failureReason ?? "Conversion job failed.");
}
await delay(Math.min(2 + attempt, 10) * 1000);
}
throw new Error(`Job ${jobId} did not complete in time.`);
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// Browser usage:
//
// const { blob } = await convertPdfToWord({
// apiKey: "YOUR_API_KEY",
// file: document.querySelector("input[type=file]").files[0],
// });
//
// const link = document.createElement("a");
// link.href = URL.createObjectURL(blob);
// link.download = "output.docx";
// link.click();