[ DWR Website | Web Application Index ]

# File Download

This is an example of downloading files via DWR

- Demo
- How it works
- Source

Please enter some text to make part of a PDF download.

Text for PDF file: |

The client code simply gets the value of the input text field and sends it to the `UploadDownload.downloadPdfFile()` server function, and when the server replies with a PDF file, we open it for download.

    function downloadPdfFile() {
      var pdftext = dwr.util.getValue('pdftext');

      UploadDownload.downloadPdfFile(pdftext, function(data) {
        dwr.engine.openInDownload(data);
      });
    }

The server function uses iText to create a PDF file, and returns it in a FileTransfer object:

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    Document document = new Document();
    PdfWriter.getInstance(document, buffer);

    document.addCreator("DWR.war using iText");
    document.open();
    document.add(new Paragraph(contents));
    document.close();

    return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray());

## HTML source:

    <input type="text" id="pdftext" value="Hello, World" size="20"/>
    <button onclick="downloadPdfFile()">Download</button>

## Javascript source:

    function downloadPdfFile() {
      var pdftext = dwr.util.getValue('pdftext');

      UploadDownload.downloadPdfFile(pdftext, function(data) {
        dwr.engine.openInDownload(data);
      });
    }

## Java source:

    public FileTransfer downloadPdfFile(String contents) throws Exception {
        if (contents == null || contents.length() == 0) {
            contents = "[BLANK]";
        }

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        Document document = new Document();
        PdfWriter.getInstance(document, buffer);

        document.addCreator("DWR.war using iText");
        document.open();
        document.add(new Paragraph(contents));
        document.close();

        return new FileTransfer("example.pdf", "application/pdf", buffer.toByteArray());
    }