This is an example of downloading files via DWR
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());
<input type="text" id="pdftext" value="Hello, World" size="20"/> <button onclick="downloadPdfFile()">Download</button>
function downloadPdfFile() {
var pdftext = dwr.util.getValue('pdftext');
UploadDownload.downloadPdfFile(pdftext, function(data) {
dwr.engine.openInDownload(data);
});
}
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());
}