We are doing the same, basically sending PDF as JSON to Android/iOS and Web-Client (so Java and Swift).

The JSON Object:

public class Attachment implements Serializable {
    private String name;
    private String content;
    private Type contentType; // enum: PDF, RTF, CSV, ...

    // Getters and Setters
}

And then from byte[] content it is set the following way:

public Attachment createAttachment(byte[] content, String name, Type contentType) {
    Attachment attachment = new Attachment();
    attachment.setContentType(contentType);
    attachment.setName(name);
    attachment.setContent(new String(Base64.getMimeEncoder().encode(content), StandardCharsets.UTF_8));
}

Client Side Java we create our own file type object first before mapping to java.io.File:

public OurFile getAsFile(String content, String name, Type contentType) {
    OurFile file = new OurFile();
    file.setContentType(contentType);
    file.setName(name);
    file.setContent(Base64.getMimeDecoder().decode(content.getBytes(StandardCharsets.UTF_8)));
    return file;
  }

And finally:

public class OurFile {
    //...
    public File getFile() {
        if (content == null) {
          return null;
        }
        try {
          File tempDir = Files.createTempDir();
          File tmpFile = new File(tempDir, name + contentType.getFileEnding());
          tempDir.deleteOnExit();
          FileUtils.copyInputStreamToFile(new ByteArrayInputStream(content), tmpFile);
          return tmpFile;
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
     }
Answer from seBaka28 on Stack Overflow
Top answer
1 of 4
3

We are doing the same, basically sending PDF as JSON to Android/iOS and Web-Client (so Java and Swift).

The JSON Object:

public class Attachment implements Serializable {
    private String name;
    private String content;
    private Type contentType; // enum: PDF, RTF, CSV, ...

    // Getters and Setters
}

And then from byte[] content it is set the following way:

public Attachment createAttachment(byte[] content, String name, Type contentType) {
    Attachment attachment = new Attachment();
    attachment.setContentType(contentType);
    attachment.setName(name);
    attachment.setContent(new String(Base64.getMimeEncoder().encode(content), StandardCharsets.UTF_8));
}

Client Side Java we create our own file type object first before mapping to java.io.File:

public OurFile getAsFile(String content, String name, Type contentType) {
    OurFile file = new OurFile();
    file.setContentType(contentType);
    file.setName(name);
    file.setContent(Base64.getMimeDecoder().decode(content.getBytes(StandardCharsets.UTF_8)));
    return file;
  }

And finally:

public class OurFile {
    //...
    public File getFile() {
        if (content == null) {
          return null;
        }
        try {
          File tempDir = Files.createTempDir();
          File tmpFile = new File(tempDir, name + contentType.getFileEnding());
          tempDir.deleteOnExit();
          FileUtils.copyInputStreamToFile(new ByteArrayInputStream(content), tmpFile);
          return tmpFile;
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
     }
2 of 4
3

Yes so the problem was with the client.

while decoding we should use

byte[] decodedBytes = Base64.decodeBase64(fileJson.getString("fileContent"));

rather than

byte[] decodedBytes = Base64.decodeBase64(fileJson.get("fileContent").toString());

Since encoded data.toString() yields some think else

Also replaced encodeBase64URLSafeString with encodeBase64String Well quite a simple solution :)

Discussions

Java/Spring - Send Post Request to retrieve a PDF-File from anoter Rest Endpoint - Stack Overflow
I would like to do a simple POST-Http-Request in Java, with an Object as Payload (Serialized as JSON - I have the Gson Library included). The Endpoint retrieves a PDF-File depending on the JSON-Pay... More on stackoverflow.com
🌐 stackoverflow.com
October 17, 2020
How to send a pdf file in Post method of rest API
Hello Community, I want to post a file to one api, but i am not sure how can i do it using uipath Http request activity. I am able to send the file in the postman tool using the api. My api is "http://api.xyz/{apikey}/process. I want to send a pdf file to this api. More on forum.uipath.com
🌐 forum.uipath.com
2
1
September 30, 2019
Sample code to send pdf file via rest api | OneSpan Community Platform
Hello, I want to send a pdf file using e-sign. I sent a file (by creating transaction) using sandbox account manually and I want to do the same via rest api. But I am not able to figure out the json content for the sender and signer details in plsql. More on community.onespan.com
🌐 community.onespan.com
June 27, 2019
java - Display pdf in browser using a rest service - Stack Overflow
REST web services method to display pdf file in browser · But in this way the pdf file is downloaded. I would prefer it to be displayed in the browser first and then if the user wants he could download it later. (sorry for the duplicate question, but as you can see the above question has not been answered... ) ... @GET @Path("/pdf") @Produces("application/pdf") public javax... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 72435372 › how-to-send-pdf-file-on-response
java - How to send PDF file on response - Stack Overflow
So first of all you need to change your api to return ResponseEntity and convert your resulted pdf into byte array. I'll attach a code snippet as an example · public static ResponseEntity<Resource> makeResponse(byte[] file, String filename, ...
🌐
Pega
support.pega.com › question › mapping-connect-rest-receiving-pdf-file-sent-bodypayload
Mapping Connect REST - receiving PDF file sent in the Body/Payload | Support Center
May 26, 2023 - https://docs-previous.pega.com/data-management-and-integration/87/configuring-rest-connector-receive-binary-attachments · I'm using Java Object property type (BinaryPDF) to map the API response. Then, I'm using the following Java step in the Activity: This is partially working because it allows me to send the PDF to the browser:
🌐
Stack Overflow
stackoverflow.com › questions › 64404821 › java-spring-send-post-request-to-retrieve-a-pdf-file-from-anoter-rest-endpoint
Java/Spring - Send Post Request to retrieve a PDF-File from anoter Rest Endpoint - Stack Overflow
October 17, 2020 - @PostMapping(path = "/print") public String printCompetences(@RequestBody final PrintCompetences competences) throws IOException, InterruptedException { Gson gson = new Gson(); String requestPayLoad = gson.toJson(competences); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:5001")) .POST(HttpRequest.BodyPublishers.ofString(requestPayLoad)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); return gson.toJson(response.body()); } ... Should the response.body() contain the PDF binary or what?
🌐
UiPath Community
forum.uipath.com › help
How to send a pdf file in Post method of rest API - Help - UiPath Community Forum
September 30, 2019 - Hello Community, I want to post a file to one api, but i am not sure how can i do it using uipath Http request activity. I am able to send the file in the postman tool using the api. My api is "http://api.xyz/{apikey}…
🌐
Onespan
community.onespan.com › forum › sample-code-send-pdf-file-rest-api
Sample code to send pdf file via rest api | OneSpan Community Platform
June 27, 2019 - For two questions: (1)elaboration of the file sending: - first I created a v_file object by assigning the path · v_file bfile := bfilename('MYDIR', 'SampleDoc.pdf'); - then loaded the file to a blob:
Find elsewhere
🌐
Google Groups
groups.google.com › g › restygwt › c › 938lxPAUliI
REST Response as application/pdf
Thank you guys - Especially christian for your help! The way Decio did it sounds pretty cool, but it is overkill for me. I split it into 2 requests too now. One Rest to get a "real" url on my Tomcat /temp and one DownloadServlet which serves the File as Application/pdf.
🌐
Qoppa
kbdeveloper.qoppa.com › rest-api-create-and-upload-pdf
Rest API Create and Upload PDF / Image or Word Doc – Knowledge Base – Qoppa Java PDF API SDK & Server Products
October 21, 2016 - PUT http://{host}:{port}/qoppapdf/v1/documents/mydir/mydoc.pdf Content-Type: application/pdf (PDF file in message body) · PUT http://{host}:{port}/qoppapdf/v1/documents/mydir/jpeg.pdf Content-Type: image/jpeg (image file in message body) · PUT http://{host}:{port}/qoppapdf/v1/documents/m...
🌐
Level Up Lunch
leveluplunch.com › java › tutorials › 032-return-file-from-spring-rest-webservice
Return file from REST webservice | Level Up Lunch
June 1, 2015 - @RestController public class DownloadPDFController { } ... In the DownloadPDFController we will create a default request mapping for the application. The return type will be a ResponseEntity, an extension of HttpEntity that adds a HttpStatus ...
Top answer
1 of 3
1

Try this

            HttpResponse response = HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(strPath));
            response.TransmitFile(strPath); //File
            response.Flush();
            response.End();
            Response.ContentType = ContentType;
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(strPath));
            Response.WriteFile(strPath);
            Response.End();
2 of 3
0

Here is a spring boot example. you can refer this example https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-first-application.html and attach the below class in the project

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;
import java.io.File;
import java.nio.file.Files;
@Controller
public class DemoController {

    @RequestMapping(value="/getpdf", method=RequestMethod.GET)
    public ResponseEntity<byte[]> getPDF() {
        File file = new File("sample.pdf"); // change to relative path
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_PDF);
        String filename = "output.pdf";
        headers.setContentDispositionFormData(filename, filename);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = null;
        try {
            response = new org.springframework.http.ResponseEntity<>(Files.readAllBytes(file.toPath()), headers, org.springframework.http.HttpStatus.OK);
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}