Manvendra Singh
Manvendra Singh

Reputation: 51

How to download pdf just after creating it in java

i'm using java and I create a pdf file from database. And now i want to make it download for the user automatically. When user hit that servlet page. here is my some code...

            /* 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();

Upvotes: 0

Views: 454

Answers (1)

Amit Kumar Lal
Amit Kumar Lal

Reputation: 5779

Here is the sample code you need to put in your servlet method to make the file downloadable.

   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);
                }
            }

Upvotes: 2

Related Questions