Java realizes PDF online preview function of four ways

  • 2021-12-04 18:49:11
  • OfStack

Directory Java Realization PDF Online Preview Java Quick Realization PDF Online Preview

Java Realizes PDF Online Preview


    @RequestMapping("/preview1")
    public void er(HttpServletResponse response){
        File file = new File("G:\\ Desktop \\Thymeleaf3.0 Chinese translation document @www.java1234.com.pdf");
        if (file.exists()){
            byte[] data = null;
            try {
                FileInputStream input = new FileInputStream(file);
                data = new byte[input.available()];
                input.read(data);
                response.getOutputStream().write(data);
                input.close();
            } catch (Exception e) {
                System.out.println(e);
            }
        }else{
            return;
        }
    }
    @ResponseBody
    @RequestMapping("/preview2")
    public void findPdf( HttpServletResponse response) throws IOException{
        response.setContentType("application/pdf");
        FileInputStream in = new FileInputStream(new File("G:\\ Desktop \\Thymeleaf3.0 Chinese translation document @www.java1234.com.pdf"));
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[512];
        while ((in.read(b))!=-1) {
            out.write(b);
        }
        out.flush();
        in.close();
        out.close();
    }
    @ResponseBody
    @RequestMapping("/preview3")
    public void devDoc(HttpServletRequest request, HttpServletResponse response, String storeName) throws Exception {
        request.setCharacterEncoding("UTF-8");
        String ctxPath = request.getSession().getServletContext().getRealPath("");
        String downLoadPath = "G:\\ Desktop \\Thymeleaf3.0 Chinese translation document @www.java1234.com.pdf";
        response.setContentType("application/pdf");
        FileInputStream in = new FileInputStream(new File(downLoadPath));
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        while ((in.read(b))!=-1) {
            out.write(b);
        }
        out.flush();
        in.close();
        out.close();
    }
    @ResponseBody
    @RequestMapping("/preview")
    public void download( HttpServletResponse response
                        ) throws IOException {
        String filePath = "G:\\ Desktop \\Thymeleaf3.0 Chinese translation document @www.java1234.com.pdf";
        System.out.println("filePath:" + filePath);
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] bs = new byte[1024];
        int len = 0;
        response.reset(); //  Very important 
        if (true) { //  Online opening mode 
            URL u = new URL("file:///" + filePath);
            String contentType = u.openConnection().getContentType();
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "inline;filename="
                    + "2019 English in the first half of 4 Grade I written test admission ticket ( Dai Linfeng ).pdf");
            //  The file name should be encoded to utf-8 Note: When used, we can ignore this sentence 
        } else {
            //  Pure download mode 
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + "2019 English in the first half of 4 Grade I written test admission ticket ( Dai Linfeng ).pdf");
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(bs)) > 0) {
            out.write(bs, 0, len);
        }
        out.flush();
        out.close();
        br.close();
    }

Java Quick Realization of PDF Online Preview

This article uses the kernel of each browser to support PDF preview function to do, PDF preview on the Internet said the most is PDF. JS preview, also found a lot of articles, life or death finally can not be achieved, through this method to solve, if there is PDF. js solution can be communicated with everyone.

It is mentioned here that other word and excel can be transcoded into PDF by aspose, which is also effective quickly. You can search it online.

The method is very simple. First of all, IO packages are introduced.


import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;

The next step is to write a method in your background controller. Inside file files can be obtained through parameters or encapsulation, the flow inside does not need to be closed, the browser will automatically obtain and then display. If you close it, the browser will not load!


@RequestMapping(value = "/showpdf")
    public void showpdf(HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            File file = new File("D:/xyptFile/java.pdf");
            FileInputStream fileInputStream = new FileInputStream(file);
            response.setHeader("Content-Type", "application/pdf");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

Article source: Test and verify from other articles to obtain the best scheme.


Related articles: