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
java - Send application/pdf content with http call - Stack Overflow
1 How to send a PDF to the browser from a Java webapplication? 9 Sending a pdf file to client from server through web service More on stackoverflow.com
🌐 stackoverflow.com
March 3, 2022
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
java - Passing pdf data through REST - Stack Overflow
How to pass the whole pdf content as response in Restful web services using java platform. I tried with converting the responses to String and byte array. First case, got registered expression erro... 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, ...
🌐
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?
🌐
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:
Find elsewhere
🌐
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:
🌐
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 ...
🌐
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.
🌐
Coderanch
coderanch.com › t › 523284 › java › sending-pdf-attachment-java-webservice
sending pdf or any attachment from a java webservice to java client using JAX-WS and SAAJ (Web Services forum at Coderanch)
2. Implementing SwA (usage of DataHandler) is not supported by WS Basic Profile (1.1 or 2.0). You must check if it is supported by Attachments Profile 1.1 before interoperating your web service from other than java language. Implementing "In-line" or MTOM attachments is though interoperable (as it conforms to the WS Basic Profile), there are attachment content size limitations. 3. If you use "In-line" or MTOM attachments, then there are obviously restrictions on attachment content, which I presume due to JVM memory restrictions. But, using SwA though there are size restrictions you can atleast send bigger files compared to former approach.
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;
    }
}
🌐
Qoppa
kbdeveloper.qoppa.com › jpdfprocess-rest-api-to-manipulate-pdf-documents
J2EE Server Rest API to Run PDF Processes – Knowledge Base – Qoppa Java PDF API SDK & Server Products
April 16, 2015 - Edit the restConfig.xml file (supplied) with the license for jPDFProcess and the path of the REST storage directory created in step (a). Configure your servlet container with a Java system property named PDFREST_CONFIG which has as its value the path to the restConfig.xml file.