Skip to content

Commit 3fe7005

Browse files
Add +server convertPdf route and requestPdfConversion.ts
1 parent 02b4208 commit 3fe7005

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { MATHPIX_APP_ID, MATHPIX_APP_KEY } from "$env/static/private";
2+
3+
type MathpixOptions = {
4+
conversion_formats: {
5+
'md': boolean;
6+
'docx': boolean;
7+
'tex.zip': boolean;
8+
'html': boolean;
9+
};
10+
math_inline_delimiters: string[];
11+
rm_spaces: boolean;
12+
};
13+
14+
const defaultOptions: MathpixOptions = {
15+
conversion_formats: {
16+
'md': true,
17+
'docx': false,
18+
'tex.zip': false,
19+
'html': false,
20+
},
21+
math_inline_delimiters: ['$', '$'],
22+
rm_spaces: true,
23+
};
24+
25+
// See https://docs.mathpix.com/#process-a-pdf
26+
async function requestPdfConversion(file: Blob, option: MathpixOptions = defaultOptions): Promise<string> {
27+
const BASE_URL = 'https://api.mathpix.com/v3';
28+
const headers = {
29+
'app_id': MATHPIX_APP_ID,
30+
'app_key': MATHPIX_APP_KEY
31+
};
32+
33+
// Start the conversion
34+
const formData = new FormData();
35+
formData.append('file', file);
36+
formData.append('options_json', JSON.stringify(option));
37+
38+
const initialResponse = await fetch(`${BASE_URL}/pdf`, {
39+
method: 'POST',
40+
headers: headers,
41+
body: formData
42+
});
43+
44+
const { pdf_id } = await initialResponse.json();
45+
46+
// Check conversion status
47+
let conversionCompleted = false;
48+
while (!conversionCompleted) {
49+
const statusResponse = await fetch(`${BASE_URL}/converter/${pdf_id}`, {
50+
method: 'GET',
51+
headers: headers
52+
});
53+
54+
const statusData = await statusResponse.json();
55+
if (statusData.status === "completed") {
56+
conversionCompleted = true;
57+
} else {
58+
// Wait for a 1 second before polling again
59+
await new Promise(resolve => setTimeout(resolve, 1000));
60+
}
61+
}
62+
63+
// Fetch the markdown data
64+
const markdownResponse = await fetch(`${BASE_URL}/converter/${pdf_id}.md`, {
65+
method: 'GET',
66+
headers: headers
67+
});
68+
69+
return await markdownResponse.text();
70+
}
71+
72+
export { requestPdfConversion };

src/routes/convertPdf/+server.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { requestPdfConversion } from '$lib/server/pdfconvert/requestPdfConversion';
2+
import { json } from '@sveltejs/kit';
3+
4+
export async function POST({ request }) {
5+
const blob = await request.blob()
6+
const result = await requestPdfConversion(blob);
7+
return json({ result }, { status: 201 });
8+
}

0 commit comments

Comments
 (0)