PDFApi.java 1.98 KB
Newer Older
1
package web.multitask.trismegistoservices.api;
2 3

import org.json.JSONObject;
4
import org.springframework.core.io.Resource;
5
import org.springframework.http.HttpHeaders;
6
import org.springframework.http.MediaType;
7 8
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
9
import lombok.AllArgsConstructor;
10
import web.multitask.trismegistoservices.services.PDFService;
11
import web.multitask.trismegistoservices.utils.CommonUtils;
12 13 14

@RestController
@CrossOrigin(origins = "*")
15
@RequestMapping("/pdf")
16
@AllArgsConstructor
17 18 19
public class PDFApi {

    PDFService pdfService;
20
    CommonUtils commonUtils;
21 22

    @PostMapping("/public/html")
23
    public ResponseEntity<?> htmlToPdf(@RequestBody String json) {
24
        try {
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

            JSONObject jsonBody = new JSONObject(json);
            byte[] bytes = pdfService.generatePdf(jsonBody.getString("html"));

            if(jsonBody.optBoolean("base64")){
                String base64 = commonUtils.byteToBase64(bytes);
                return ResponseEntity.ok().body(
                    new JSONObject()
                    .put("base64", base64)
                    .put("file_name", jsonBody.optString("file_name", "pdf.pdf"))
                    .put("status", true)
                    .put("message", "OK")
                );
            }else{
                Resource resource = commonUtils.byteToResource(bytes, jsonBody.optString("file_name", "no_name.pdf"));
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + jsonBody.optString("file_name", "no_name.pdf"));
                return ResponseEntity.ok()
                .headers(headers)
                .contentLength(bytes.length)
                .contentType(MediaType.APPLICATION_PDF)
                .body(resource);
47
            }
48 49
        }catch (Exception e){
            System.out.println(e);
50
            return ResponseEntity.internalServerError().body(e.getMessage());
51 52 53 54
        }
    }

}