无需@RequestMapping实现已生成PDF文件的下载方案问询
解决方案
1. 修改PDF生成方法,返回PDF字节数组
调整PDFCreator类的createPDF方法,让它返回生成的PDF字节数据,以便后续直接用这些数据触发下载:
package eu.demo; import java.io.ByteArrayOutputStream; import java.util.Date; import com.vaadin.ui.Notification; import eu.demo.model.Alleles; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; public class PDFCreator { private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD); // 修改方法签名,返回byte数组 public static byte[] createPDF(Alleles selected) { ByteArrayOutputStream baos = null; try { Document doc = new Document(); baos = new ByteArrayOutputStream(); PdfWriter.getInstance(doc, baos); doc.open(); doc.add(new Paragraph("你的等位基因信息:\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(); Notification.show("PDF已生成"); // 返回PDF字节数组 return baos.toByteArray(); } catch (Exception e) { e.printStackTrace(); Notification.show("PDF生成失败"); return null; } finally { if (baos != null) { try { baos.close(); } catch (Exception ignored) {} } } } }
2. 在保存按钮点击事件中添加下载逻辑
从代码中的com.vaadin.ui.Notification可判断你使用的是Vaadin 8版本,直接用Vaadin内置的StreamResource和FileDownloader实现按钮触发下载,无需依赖Spring请求映射:
import com.vaadin.ui.Button; import com.vaadin.server.StreamResource; import com.vaadin.server.FileDownloader; import java.io.ByteArrayInputStream; // 在主视图的保存按钮初始化处添加点击事件 saveButton.addClickListener(event -> { // 1. 先执行保存到数据库的逻辑 saveAlleleToDatabase(selectedAllele); // 2. 生成PDF字节数组 byte[] pdfBytes = PDFCreator.createPDF(selectedAllele); if (pdfBytes == null) { return; } // 3. 创建下载资源 StreamResource pdfResource = new StreamResource( () -> new ByteArrayInputStream(pdfBytes), "allele-info-" + selectedAllele.getName() + ".pdf" // 自定义下载文件名 ); // 4. 绑定下载器到按钮并触发下载 FileDownloader downloader = new FileDownloader(pdfResource); downloader.extend(saveButton); downloader.download(); });
关键说明
StreamResource:直接基于内存中的字节数组创建下载资源,无需生成本地文件FileDownloader:Vaadin提供的组件,用于将下载逻辑绑定到按钮,点击时直接触发浏览器下载- 整个流程不需要后端接口URI,完全在前端按钮点击事件中完成,符合你的项目结构限制
内容的提问来源于stack exchange,提问作者Andrea
相关产品推荐
相关产品推荐

