在Java中创建后如何下载pdf

时间:2019-05-30 11:33:18

标签: java file servlets document

我正在使用Java,我从数据库中创建了一个pdf文件。 现在,我想让它自动为用户下载。 当用户点击该servlet页面时。 这是我的一些代码...

            /* Define the SQL query */
            ResultSet rs=st.executeQuery("SELECT Id,Name FROM student");
            Document my_pdf_report = new Document();
            my_pdf_report.open();            
            //we have four columns in our table
            PdfPTable my_report_table = new PdfPTable(2);
            //create a cell object
            PdfPCell table_cell;
            while (rs.next()) {                
                            String id = rs.getString("Id");
                            table_cell=new PdfPCell(new Phrase(id));
                            my_report_table.addCell(table_cell);
                            String name=rs.getString("Name");
                            table_cell=new PdfPCell(new Phrase(name));
                            }
            /* Attach report table to PDF */
            my_pdf_report.add(my_report_table);  
            Document pdf =new Document();
            pdf=my_pdf_report;
            my_pdf_report.close();
            /* Close all DB related objects */
            rs.close();
            st.close(); 
            connected.close();

1 个答案:

答案 0 :(得分:1)

这是您需要放入servlet方法中以使文件可下载的示例代码。

   resp.setContentType("text/plain");
            resp.setHeader("Content-disposition", "attachment; filename=sample.txt"); //use your file name to be displayed when downloaded

            try(InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt"); // location of file 
              OutputStream out = resp.getOutputStream()) {

                byte[] buffer = new byte[ARBITARY_SIZE];

                int numBytesRead;
                while ((numBytesRead = in.read(buffer)) > 0) {
                    out.write(buffer, 0, numBytesRead);
                }
            }