簡體   English   中英

如何使用 Servlet 作為響應發送 PDF 文件數據?

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

我的要求是使用 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();
    }
}

您必須使用ServletOutputStream及其write()方法將字節寫入響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM