File size: 1,543 Bytes
e7f7858
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { NextResponse } from 'next/server';

/**
 * GET /api/pdf-proxy?url=<encoded_pdf_url>
 * Proxies a PDF from an external URL to bypass CORS restrictions.
 * Returns the PDF with correct Content-Type so PDF.js can render it.
 */
export async function GET(request) {
    const { searchParams } = new URL(request.url);
    const pdfUrl = searchParams.get('url');

    if (!pdfUrl) {
        return NextResponse.json({ error: 'Missing url parameter' }, { status: 400 });
    }

    try {
        const res = await fetch(pdfUrl, {
            headers: {
                'User-Agent': 'Mozilla/5.0 (compatible; AnnotationTool/1.0)',
            },
            signal: AbortSignal.timeout(30000), // 30s timeout
        });

        if (!res.ok) {
            return NextResponse.json(
                { error: `PDF fetch failed: HTTP ${res.status}` },
                { status: res.status }
            );
        }

        const pdfBuffer = await res.arrayBuffer();

        return new Response(pdfBuffer, {
            status: 200,
            headers: {
                'Content-Type': 'application/pdf',
                'Content-Length': pdfBuffer.byteLength.toString(),
                'Cache-Control': 'public, max-age=86400', // cache 24h
                'Access-Control-Allow-Origin': '*',
            },
        });
    } catch (error) {
        console.error('PDF proxy error:', error);
        return NextResponse.json(
            { error: 'Failed to proxy PDF: ' + error.message },
            { status: 500 }
        );
    }
}