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

标签 java ios jakarta-ee servlets

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

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

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

我的方法对吗?请指教。

谢谢。

最佳答案

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

关于java - 如何使用 Servlet 发送 PDF 文件数据作为响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16977274/

相关文章:

java - Hadoop-1.0.1中的java.lang.NoClassDefFoundError

ios - swift 5 : index out of range when returning the array count from tableView numberOfRowsInSection

ios - 为什么 LabelFont 不能以 "\n"开始新行

java - 如何学习使用内容存储库和 Apache JackRabbit?

tomcat - 持久化交易型值(value)?

hibernate - EJB 3 或 Hibernate 3

java - 如何为自定义 Spring Batch Reader 编写 junit

java - 如何将阿拉伯语csv加载到MYSQL

iphone - 如何将应用程序添加到 "Open In"菜单 iOS

java - Android Studio自动生成getters和setters时如何同时生成注释