Easwaramoorthy Kanagaraj
Easwaramoorthy Kanagaraj

Reputation: 4213

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

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

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.

Upvotes: 4

Views: 25870

Answers (2)

Amit Verma
Amit Verma

Reputation: 81

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

Upvotes: 6

AllTooSir
AllTooSir

Reputation: 49352

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

Upvotes: 5

Related Questions