# Riassumere PDF con JavaScript e Node.js — Tutorial API

Chiama l'API di PDF Summarizer da Node.js (o da qualsiasi runtime JavaScript lato server) usando semplicemente fetch e FormData. Questo tutorial copre la prima richiesta, lo streaming, un piccolo endpoint Express per la tua applicazione e la gestione degli errori.

## Key facts

- Funziona con Node.js 18+ (fetch, FormData, Blob integrati) — nessun SDK necessario.
- POST https://pdf-summarize.com/api/summarize.php, multipart/form-data, campo file, intestazione Authorization: Bearer sk_....
- Opzioni: length, format, outputLang, includeKeywords.
- Aggiungi ?stream=1 e leggi il corpo della risposta come Server-Sent Events.
- Non esporre mai la tua chiave nel codice del browser — fai da proxy per le richieste tramite il tuo server.

## La tua prima richiesta in Node.js

1. **Ottieni una chiave API gratuita** — Registrati e copiala dalla tua dashboard.
2. **Salvala in una variabile d'ambiente** — PDF_SUMMARIZE_KEY.
3. **Crea un FormData** — Aggiungi il PDF come Blob sotto il campo file.
4. **Invia una richiesta POST e leggi il JSON.** — 

```js
// summarize.mjs — node summarize.mjs report.pdf
import { readFile } from 'node:fs/promises';
import { basename } from 'node:path';

const API_URL = 'https://pdf-summarize.com/api/summarize.php';
const KEY = process.env.PDF_SUMMARIZE_KEY;

export async function summarizePdf(path, { length = 'medium', format = 'bullets', outputLang = 'auto' } = {}) {
  const form = new FormData();
  form.append('file', new Blob([await readFile(path)], { type: 'application/pdf' }), basename(path));
  form.append('length', length);
  form.append('format', format);
  form.append('outputLang', outputLang);

  const res = await fetch(API_URL, {
    method: 'POST',
    headers: { Authorization: `Bearer ${KEY}` },
    body: form,
    signal: AbortSignal.timeout(180_000),
  });
  const data = await res.json();
  if (!res.ok || !data.success) throw new Error(`${res.status}: ${data.error ?? JSON.stringify(data)}`);
  return data;
}

const result = await summarizePdf(process.argv[2]);
console.log(result.summary);
console.log(`${result.page_count} pagine, ${result.processing_time}s, ${result.requests_remaining} richieste rimanenti`);
```

## Streaming del riassunto

```js
export async function streamSummary(path, onText) {
  const form = new FormData();
  form.append('file', new Blob([await readFile(path)], { type: 'application/pdf' }), basename(path));
  form.append('length', 'long');

  const res = await fetch(API_URL + '?stream=1', { method: 'POST', headers: { Authorization: `Bearer ${KEY}` }, body: form });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);

  const decoder = new TextDecoder();
  let buffer = '';
  for await (const chunk of res.body) {
    buffer += decoder.decode(chunk, { stream: true });
    const lines = buffer.split('\n');
    buffer = lines.pop();
    for (const line of lines) {
      if (!line.startsWith('data: ')) continue;
      const payload = line.slice(6);
      if (payload === '[DONE]') return;
      const event = JSON.parse(payload);
      if (event.error) throw new Error(event.error);
      if (event.type === 'summary') onText(event.content);
    }
  }
}

await streamSummary('paper.pdf', (t) => process.stdout.write(t));
```

## Un endpoint Express per la tua app

Il tuo front-end effettua l'upload al **tuo** server, che aggiunge la chiave e inoltra il file:

```js
import express from 'express';
import multer from 'multer';

const app = express();
const upload = multer({ limits: { fileSize: 20 * 1024 * 1024 } });

app.post('/summarize', upload.single('file'), async (req, res) => {
  if (!req.file) return res.status(400).json({ error: 'Nessun file' });
  const form = new FormData();
  form.append('file', new Blob([req.file.buffer], { type: 'application/pdf' }), req.file.originalname);
  form.append('length', req.body.length ?? 'medium');
  const r = await fetch('https://pdf-summarize.com/api/summarize.php', {
    method: 'POST', headers: { Authorization: `Bearer ${process.env.PDF_SUMMARIZE_KEY}` }, body: form,
  });
  res.status(r.status).json(await r.json());
});

app.listen(3000);
```

## Gestione degli errori

| Stato | Significato |
|---|---|
| 400 | File mancante, non un PDF o limite di pagine superato |
| 401 | Chiave mancante o non valida |
| 413 | File troppo grande |
| 422 | Nessun testo leggibile nel PDF |
| 429 | Limite di richieste o quota raggiunta — riprova più tardi con backoff |
| 500 | Errore di riassunto temporaneo — riprova |

> **Guarda il motore in azione** — Prova lo strumento web gratuito con uno dei tuoi PDF.

## FAQ

### Posso chiamare l'API direttamente dal browser?

Tecnicamente sì, ma la tua chiave sarebbe visibile a chiunque. Inoltra le richieste tramite il tuo backend come nell'esempio con Express.

### Funziona con Deno, Bun o Cloudflare Workers?

Sì — qualsiasi runtime con supporto nativo a fetch e FormData funziona allo stesso modo.

### Esiste un SDK TypeScript?

Non ancora. L'API è costituita da un singolo endpoint multipart, quindi è sufficiente un piccolo wrapper tipizzato attorno a fetch.

### Dove si trova la documentazione completa?

Nella documentazione API, con tutti i parametri ed esempi in diverse lingue.

---
Source: https://pdf-summarize.com/it/guides/pdf-summary-api-javascript — PDF Summarizer (free PDF summarizer, Q&A with page citations, OCR, REST API). Site overview: https://pdf-summarize.com/llms.txt
