How to download pdf file and redirect to home page in Spring mvc

sanjeet pal :

Following code just work fine there is no error in it but not work as required..

problem 1: I want to download pdf file and redirect to home page(url:../).when ever i nevigate to url(../admin/generate_pdf)

problem 2:when ever i uncomment the commented line in Pdfdemo.java it gives me an error 404 page not found.

Pdfdemo.java

public class Pdfdemos {
    private static String USER_PASSWORD = "password";
    private static String OWNER_PASSWORD = "lokesh";

        public String generate_pdf() {
            try {
                String file_name="d:\\sanjeet7.pdf";
                Document document= new Document();
                PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(file_name));

//              writer.setEncryption(USER_PASSWORD.getBytes(),
//                          OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING |PdfWriter.ALLOW_ASSEMBLY|
//                          PdfWriter.ALLOW_COPY|
//                          PdfWriter.ALLOW_DEGRADED_PRINTING|
//                          PdfWriter.ALLOW_FILL_IN|
//                          PdfWriter.ALLOW_MODIFY_ANNOTATIONS|
//                          PdfWriter.ALLOW_MODIFY_CONTENTS|
//                          PdfWriter.ALLOW_SCREENREADERS|
//                          PdfWriter.ALLOW_ASSEMBLY|
//                          PdfWriter.ENCRYPTION_AES_128, 0);


                document.open();
                document.add(new Paragraph(" "));document.add(new Paragraph(" "));
                String days_in_week[]= {"monday","tuesday","webnesday","thursday","friday","saturday"};
                int period=8;
                String user="springstudent";
                String pass="springstudent";
                String jdbcUrl="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false";
                String driver="com.mysql.jdbc.Driver";
                Connection myconn=DriverManager.getConnection(jdbcUrl,user,pass);
                PreparedStatement ps=null;
                ResultSet rs=null;
                String query="select * from class_t";
                ps=myconn.prepareStatement(query);
                rs=ps.executeQuery();
                while(rs.next()) {
                    Paragraph para=new Paragraph("Time table for class"+rs.getString("class")+rs.getString("section"));
                    document.add(para);
                    System.out.println(rs.getInt("id"));
                    PdfPTable table=new PdfPTable(period+1);
                    for(int i=0;i<days_in_week.length;i++) {

                        for(int j=0;j<period+1;j++) {

                            if(j==5) {
                                table.addCell("recess");
                            }else {

                                table.addCell("this is "+j);
                            }


                        }


                    }
                    document.add(table);
                    document.newPage();

                }
                document.close();
                System.out.println("finish");





            return file_name;

            }catch(Exception e) {
                System.out.println(e);
            }
            return null;


        }

}

Generate_pdf_controller.java

@Controller
@RequestMapping("/admin/generate_pdf")
public class Generate_pdf_Controller {


    @GetMapping("/online")
    public String generating_pdf(Model theModel) {
        System.out.println("hello");
        CustomerServiceImpl pal=new CustomerServiceImpl();
        Pdfdemos pal1=new Pdfdemos();
        String xx=pal1.generate_pdf();
        return "redirect:/";
    }
}
xerx593 :

Just to get the pdf (download into browser from local file system), this code is sufficient:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/admin/generate_pdf")
public class PdfController {

    @GetMapping(value = "/online", /*this is "nice to have" ->*/ produces = MediaType.APPLICATION_PDF_VALUE)
    @ResponseBody // this is important, as the return type byte[]
    public byte[] generating_pdf() throws IOException {//exception handling...
        System.out.println("hello");//logging
        // re-generate new file if needed (thread-safety!)...
        // ..and dump the content as byte[] response body:
        return Files.readAllBytes(Paths.get("d:\\sanjeet7.pdf"));
    }
}

... if you need "a refresh", you can "rewrite" the file/re-call your service, but still maybe not the "thread-safest" solution.

Edit: With no further configuration (port/context root/...), You should reach this at: http://localhost:8080/admin/generate_pdf/online


If you want to "operate closer to the bytes" and with void return type/no @ResponseBody and want an additional redirect (to be tested), I think this should still work:

@Controller
public class ... {

   @GetMapping(value = ..., produces ...)
   //no request body, void return type, response will be autowired and can be handled
   public void generatePdf(javax.servlet.http.HttpServletResponse response) throws ... {
      java.io.OutputStream outStr = response.getOutputStream();
      // dump from "somewhere" into outStr, "finally" close.
      outStr.close();
      //TO BE TESTED:
      response.sendRedirect("/");
   }
}

..or even (return a "view name" + operate on outputStream):

   @GetMapping(value = ..., produces = "application/pdf")
   //return a "view name" (!), and you can inject (only) the outputstream (without enclosing response) 
   public String generatePdf(java.io.OutputStream outputstream) throws... {          
      // ... do your things on outputstream, IOUtils is good...
      // close the stream(?)
      // ..and
      return "redirect:/"; // to a redirect or a view name.
      // .... (in a "spring way", which could also save you some "context path problems"
   } ...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12487&siteId=1