Question on Java Servlet to open a PDF file using iText

前端 未结 3 1344
北海茫月
北海茫月 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:35

    When you use PdfStamper it is reading in the file from the disk and writing it to baos. When you removed the PdfStamper, baos NEVER GETS WRITTEN TO. So of course, baos is empty, so never actually returns anything.

    EDIT: you want to actually do this (the PdfReader is only necessary if you want to modify the PDF):

    private static void copy(InputStream is, OutputStream os) throws IOException
    {
        byte buffer[] = new byte[8192];
        int bytesRead, i;
    
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
                FileInputStream baos = new FileInputStream(DOCUMENT_LOCATION);
    
                // 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");
                response.setContentLength(new File(DOCUMENT_LOCATION).length());
    
                OutputStream os = response.getOutputStream();
                copy(baos, os);
                os.flush();
                os.close();
    
            }
        } 
    

提交回复
热议问题