java 如何使用 Servlet 作为响应发送 PDF 文件数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16977274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:36:23  来源:igfitidea点击:

How to send PDF file data as a response using Servlet?

javaiosjakarta-eeservlets

提问by Easwaramoorthy K

My requirement is responding the PDF data to the mobile client(iPhone) using HTTP Servlet.

我的要求是使用 HTTP Servlet 将 PDF 数据响应到移动客户端(iPhone)。

I did in the following way, But I am not getting expected output in the client.

我按以下方式做了,但我没有在客户端得到预期的输出。

    PrintWriter out = response.getWriter();

    String aInputFileName = "/Users/hcl/Desktop/Easwar/sample.pdf";
        log("Reading in binary file named : " + aInputFileName);
        File file = new File(aInputFileName);
        log("File size: " + file.length());
        byte[] result = new byte[(int)file.length()];
        System.out.println("Length : "+  result.length);
        try {
          InputStream input = null;
          try {
            int totalBytesRead = 0;
            input = new BufferedInputStream(new FileInputStream(file));
            while(totalBytesRead < result.length){
              int bytesRemaining = result.length - totalBytesRead;
              //input.read() returns -1, 0, or more :
              int bytesRead = input.read(result, totalBytesRead, bytesRemaining); 
              if (bytesRead > 0){
                totalBytesRead = totalBytesRead + bytesRead;
              }
            }
        response.setHeader("Content-Type", "application/pdf");

        out.println(result);

Is the method I am following right? Please advice.

我遵循的方法对吗?请指教。

Thanks.

谢谢。

回答by Amit Verma

package com.javatpoint;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.darwinsys.spdf.PDF;
import com.darwinsys.spdf.Page;
import com.darwinsys.spdf.Text;
import com.darwinsys.spdf.MoveTo;

public class ServletPDF extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        PrintWriter out = response.getWriter();
        response.setContentType("application/pdf");

        response.setHeader("Content-disposition","inline; filename='javatpoint.pdf'");

        PDF p = new PDF(out);
        Page p1 = new Page(p);
        p1.add(new MoveTo(p, 200, 700));
        p1.add(new Text(p, "www.javatpoint.com"));
        p1.add(new Text(p, "by Sonoo Jaiswal"));

        p.add(p1);
        p.setAuthor("Ian F. Darwin");

        p.writePDF();
    }
}

回答by NINCOMPOOP

You have to use ServletOutputStreamand its write()method to write bytes to the response .

您必须使用ServletOutputStream及其write()方法将字节写入响应。