Question on Java Servlet to open a PDF file using iText

前端 未结 3 1377
北海茫月
北海茫月 2021-01-24 15:34

The code below grabs a PDF file and displays it in the browser.

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputS         


        
3条回答
  •  耶瑟儿~
    2021-01-24 16:22

    If the PDF file is already exists, then you don't have to use itext. You just read data from the file and write it into OutputStream of response.

    Here is some code

    public class WelcomeServlet extends HttpServlet {
    
        private static final String DOCUMENT_LOCATION = "H:\\testPDF.pdf"; // a test pdf on my PC
    
        @Override
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        }
    
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            // set some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setContentType("application/pdf");
    
            InputStream in = new FileInputStream(DOCUMENT_LOCATION);
            OutputStream out = response.getOutputStream();
    
            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
               out.write(buf, 0, len);
            }
            in.close();
    
        }
    } 
    

提交回复
热议问题