-1

My BufferedReader corrupts my Pdf file and writes everything in the first line.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    createPdf();
    response.setHeader("Content-disposition","attachment; filename=\""+"myPdf.pdf"+"\"");
    BufferedReader reader = null;

    try {
        File file = new File("myPath\\myNewPdf.pdf");
        reader = new BufferedReader(new FileReader(file));

        String line;
        while ((line = reader.readLine()) != null) {
            response.getWriter().append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I just want to read the Pdf and write it in a new one to make it a download.

W.Tf
  • 1
  • 1
  • 1
    `BufferedReader` is not meant to read non-text files, use a lower-level class (e.g a `FileInputStream`), see : https://stackoverflow.com/questions/1442893/implementing-a-simple-file-download-servlet – Arnaud Feb 06 '19 at 08:53
  • 1
    `BufferedReader` is a `Reader`, and `Reader` is for character data. PDF files are not character data, and don't contain lines. You should be using an `InputStream`. This is all documented. – user207421 Feb 06 '19 at 08:55
  • 2
    Well, as defined in JavaDoc, the `Reader` abstract class is an _abstract class for reading character streams_ - but PDF file is a binary file, not a stream of characters. Use `InputStream` to read the file, and `response.getOutputStream()` for writing it. – Jozef Chocholacek Feb 06 '19 at 08:57

1 Answers1

-1

this did the trick thx @user207421

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        createPdf();
        response.setHeader("Content-disposition","attachment; filename=\""+"myNewPdf.pdf"+"\"");

        InputStream inputStream = new FileInputStream("myPath\\myPdf.pdf");
        int data;

        while( (data = inputStream.read()) >= 0 ) {
            response.getWriter().write(data);
        }
        inputStream.close();
    }
W.Tf
  • 1
  • 1
  • 4
    The `response.getWriter().write(data);` can cause problems later - `response.getWriter()` returns `PrintWriter`, which is again meant for output of character data, but you are writing binary data. With the current file it might work, but I would recommend using `response.getOutputStream()` for output. – Jozef Chocholacek Feb 06 '19 at 09:41