簡體   English   中英

如何在Spring mvc中下載pdf文件並重定向到主頁

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

以下代碼工作正常,沒有錯誤,但不能按要求工作..

問題 1:我想下載 pdf 文件並重定向到主頁(url:../)。當我訪問 url(../admin/generate_pdf) 時

問題 2:當我取消注釋 Pdfdemo.java 中的注釋行時,它會給我一個錯誤 404 頁面未找到。

pdf演示文件

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:/";
    }
}

創建和下載 PDF 的簡化版本:

@Service
public class PdfService {

    public InputStream createPdf() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.getInstance(document, out);

        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("My example PDF document"));
        // some logic here

        document.close();

        return new ByteArrayInputStream(out.toByteArray());
    }
}


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

    @Autowired
    private PdfService pdfService;

    @GetMapping("/online")
    public void generatePdf(HttpServletResponse response) throws Exception {
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=\"mydocument.pdf\"");

        InputStream pdf = pdfService.createPdf();
        org.apache.commons.io.IOUtils.copy(pdf, response.getOutputStream());
        response.flushBuffer();
    }
}

重定向怎么樣,正如我在評論中所說,你可以在前端使用 JS(在調用/admin/generate_pdf/online url 之后)。 您不能同時下載文件和進行刷新/重定向。

只是為了得到pdf(從本地文件系統下載到瀏覽器),這段代碼就足夠了:

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

...如果您需要“刷新”,您可以“重寫”文件/重新調用您的服務,但可能仍然不是“線程最安全”的解決方案。

編輯:無需進一步配置(端口/上下文根/...),您應該在以下位置訪問: http://localhost:8080/admin/generate_pdf/online


如果您想“操作更接近字節”並使用void返回類型/無@ResponseBody想要額外的重定向(待測試),我認為這應該仍然有效:

@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("/");
   }
}

.. 甚至(返回“視圖名稱”+ 對 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"
   } ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM