I'm creating a PDF file with some info from a grid. In particular, the user selects from a grid an allele, all the info is displayed in a form that can be modified and then, when clicked on the button "save", all the modified info is stored in the database and a PDF with all the info is created.
I managed in creating it, but I don't understand how to download it.
Because of the structure of the project I cannot use the spring @RequestMapping
since I want to trigger the download when clicking on a button and not when entering a specific URI.
Here's the code for the PDF, the function "createPDF" is called when the user click on the save button in the main view:
package eu.demo;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import com.vaadin.ui.Notification;
import eu.demo.model.Alleles;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class PDFCreator {
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
public static void createPDF(Alleles selected) {
try {
Paragraph preface = new Paragraph();
Document doc = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//OutputStream outputStream = new FileOutputStream(new File("Test.pdf"));
PdfWriter.getInstance(doc, baos);
doc.open();
doc.add(new Paragraph("Your allele info:\n", catFont));
doc.add(new Paragraph(selected.getName()+"\n"));
doc.add(new Paragraph(selected.getAllsForm()+"\n"));
doc.add(new Paragraph(selected.getAlleleType()+"\n"));
doc.add(new Paragraph(selected.getMgiRef()+"\n"));
doc.add(new Paragraph("\n\n"));
doc.close();
//outputStream.close();
baos.close();
Notification.show("PDF created");
} catch (Exception e) {
e.printStackTrace();
}
}
}