2
votes

I have a Get API by which can download PDF. Using Spring rest template I am able to get content but when I am creating PDF file it's creating a blank pdf.

I am using byte[] to create a new file.

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_PDF));
HttpEntity<String> entity = new HttpEntity<>(headers);

ResponseEntity<String> result =
restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);


String content = response.getBody();
byte[] bytes = content.getBytes();
Files.write(Paths.get("/home/123.pdf"), bytes, StandardOpenOption.CREATE );

Please suggest me anyway to do it, Finally my objective
to upload in S3.

2

2 Answers

8
votes

Your request headers should also include MediaType.APPLICATION_OCTET_STREAM

This response object will return a byte array- which will be your pdf.

So, the complete example would be something like this-

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_PDF, MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> entity = new HttpEntity<>(headers);

ResponseEntity<byte[]> result =
restTemplate.exchange(uri, HttpMethod.GET, entity, byte[].class);


byte[] content = result.getBody();
Files.write(Paths.get("/home/123.pdf"), content, StandardOpenOption.CREATE );

Hope this helps.

0
votes

You can Use PDFbox(or itext) API, which is a great way of parsing and creating PDF. It will allow you to place your text etc,

That said

    public static void writeToFIle(InputStream uploadedInputStream, String uploadedFileLocation) {

    try {
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        int read = 0;
        byte[] bytes = new byte[1024];

        out = new FileOutputStream(new File(uploadedFileLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

should be enough to create a PDF, if its blank check if the value arn't null

I personnaly use jersey to link client and server so i cant really tell you if your method to get the pdf works