---
title: "Come creare file PDF"
version: 6.1
locale: it
source: https://docs.djangoproject.com/it/6.1/howto/outputting-pdf/
canonical: https://djangodocs.dev/it/6.1/howto/outputting-pdf/
---
# Come creare file PDF

Questo documento spiega come produrre PDF dinamicamente usando le views di Django. Questo è reso possibile dall’eccellente libreria open-source [ReportLab](https://docs.reportlab.com/) Python PDF.

Il vantaggio di generare file PDF dinamicamente è che puoi creare PDF personalizzati per differenti scopi – , per differenti utenti o per differenti parti del contenuto.

Per esempio, Django è stato usato in [kusports.com](https://www2.kusports.com/) per generare bracket di torneo printer-friendly per i tornei NCAA, come file PDF, per le persone che partecipavano alla gara March Madness.

## Installa ReportLab

The ReportLab library is [available on PyPI](https://pypi.org/project/reportlab/). A [user guide](https://www.reportlab.com/docs/reportlab-userguide.pdf)
(not coincidentally, a PDF file) is also available for download.
You can install ReportLab with `pip`:

```console
$ python -m pip install reportlab
```

*Windows*

```doscon
...\> py -m pip install reportlab
```

Test your installation by importing it in the Python interactive interpreter:

```pycon
>>> import reportlab
```

Se quel comando non genera nessune errore, l’installazione ha funzionato.

## Scrivi la tua vista

La chiave per generare PDF dinamicamente con Django è che le API di ReportLab agiscono su oggetti file-like e l’oggetto di Django [`FileResponse`](/it/6.1/ref/request-response/#django.http.FileResponse) accetta oggetti file-like.

Qui un esempio di «Hello World»:

```
import io
from django.http import FileResponse
from reportlab.pdfgen import canvas

def some_view(request):
    # Create a file-like buffer to receive PDF data.
    buffer = io.BytesIO()

    # Create the PDF object, using the buffer as its "file."
    p = canvas.Canvas(buffer)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(100, 100, "Hello world.")

    # Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()

    # FileResponse sets the Content-Disposition header so that browsers
    # present the option to save the file.
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename="hello.pdf")
```

Il codice ed i commenti dovrebbero essere auto esplicativi, ma alcuni dettagli meritano un approfondimento:

- La risposta imposterà automaticamente il tipo MIME `application/pdf` basato sull’estensione del file. Questo dice ai browser che il documento è un file PDF, piuttosto che un file HTML o un contenuto binario generico `application/octet-stream`.
- Quando `as_attachment=True` viene passato a `FileResponse`, imposta l’header `Content-Disposition` appropriato e dice ai browser web di mostrare una finestra di dialogo che richiede/conferma come gestire il documento anche se sulla macchina è impostato un valore predefinito. Se il parametro `as_attachment` viene omesso, i browser gestiranno il PDF utilizzando qualsiasi programma/plugin siano stati configurati ad usare per i PDF.
- Puoi scegliere un parametro `filename` arbitrario. Verrà utilizzato dai browsers nella finestra di dialogo «Salva come..».
- È possibile agganciarsi all’API ReportLab: lo stesso buffer è passato come primo argomento alla classe `canvas.Canvas` può alimentare la classe [`FileResponse`](/it/6.1/ref/request-response/#django.http.FileResponse) .
- Si noti che tutti i metodi di generazione PDF successivi sono chiamati sull’oggetto PDF (in questo caso, `p`) – non su \`\` buffer\`\`.
- Infine, è importante chiamare `showPage()` e `save()` sul file PDF.

> **Note**
>
> ReportLab non è thread-safe. Alcuni dei nostri utenti hanno riportato strani problemi con Django view che generano PDF quando vi accedono più persone allo stesso tempo.

## Altri formati

Nota che non ci sono molti esempi specifici per i PDF – solo alcuni che usano `reportlab`. Puoi usare tecniche simili per generare ogni formato arbitario per il quale puoi trovare una libreria Python. Vedi anche [Come creare un output su CSV](/it/6.1/howto/outputting-csv/) per altri esempi e qualche tecnica da usare per generare formati basati su testo.

> **See also**
>
> Django Packages offre una [comparazione di package](https://djangopackages.org/grids/g/pdf/) che aiutano a generare file PDF da Django.
