Issues while embedding attachment in pdf

Hi Team,
I am trying to embed attachments to my pdf. I tried to follow following documentation:
Adding Attachment to PDF document|Aspose.PDF for Java_gaMjEwMTA1NzY1LjE3NDYwMDcyMDM._ga_W0DG8XJWKLMTc0NjAwNzIwMy4xLjAuMTc0NjAwNzIwMy4wLjAuMTcyMTI0OTMyMw…

My service looks like:

public void createPdfWithEmbeddedFile(String filePath, OutputStream outputStream) throws FileNotFoundException, IOException {

        // Create a new PDF document
        Document pdfDocument = new Document();

        // Add a page to the document
        Page page = pdfDocument.getPages().add();

        ClassPathResource resource = new ClassPathResource(filePath);
        if(!resource.exists()){
            throw new IllegalArgumentException("File not found: " + filePath);
        }


        FileSpecification fileSpecification = new FileSpecification((filePath) , "Sample file");
        page.setBackground(Color.getGray());
        fileSpecification.setMIMEType(getMimeType(Objects.requireNonNull(resource.getFilename())));


        pdfDocument.getEmbeddedFiles().add(fileSpecification);

        pdfDocument.save(outputStream);


    }


 private String getMimeType(String fileName){
        String extension = fileName.substring(fileName.lastIndexOf('.')+1).toLowerCase();
        switch (extension){
            case "txt": return "text/plain";
            case "pdf": return "application/pdf";
            case "doc": return "application/msword";
            case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            case "ppt": return "application/vnd.ms-powerpoint";
            case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
            case "jpg": case "jpeg": return "image/jpeg";
            case "png": return "image/png";
            default: return "application/octet-stream";
        }
    }

When i try to open embedded attachment in Adobe Acrobat Reader DC, it is throwing error:
image.png (4.4 KB)

Expected a dict object.

I did a workaround and modified my function like this:

    public void createPdfWithEmbeddedFile(String filePath, OutputStream outputStream) throws FileNotFoundException, IOException {
        // Create a new PDF document
        Document pdfDocument = new Document();

        // Add a page to the document
        Page page = pdfDocument.getPages().add();

        ClassPathResource resource = new ClassPathResource(filePath);
        if(!resource.exists()){
            throw new IllegalArgumentException("File not found: " + filePath);
        }

        byte[] fileBytes;
        try(InputStream inputStream = resource.getInputStream()){
            fileBytes = inputStream.readAllBytes();
        }



        // Create a FileSpecification object for the file to be embedded
        page.setBackground(Color.getGray());
        FileSpecification fileSpecification = new FileSpecification();
        fileSpecification.setContents(fileBytes);
        fileSpecification.setMIMEType(getMimeType(Objects.requireNonNull(resource.getFilename())));
        fileSpecification.setName(resource.getFilename());

        // Add the file to the PDF document
        pdfDocument.getEmbeddedFiles().add(fileSpecification);

        pdfDocument.save(outputStream);

    }

Now for txt files, this method is working. But for embedded pdf - all pages comes as blank. For word files getting following error:

image.png (2.9 KB)
image.png (3.6 KB)

Please guide me in correct direction

@shrisheshpratik

Is it happening with all kind of PDF files? Can you please share your sample PDF for our reference so that we can test the scenario in our environment and address it accordingly.

Hey @asad.ali

test.docx (15.0 KB)

test.pdf (51.6 KB)

These are two sample files which I am trying to embed. These files are created by using aspose only through HTML template.
We have Aspose Total License.
I am using Adobe Acrobat Reader DC to open generated pdf and checking its attachment section for interacting with embedded file. I have also tried to save the attachment first but it results in same issue.

Please let me know if you need any more information to debug the issue.

Just for reference I am attaching controller code as well.

@GetMapping("/embed-file")
    public ResponseEntity<StreamingResponseBody> createPdfWithEmbeddedFile(){

            // Set headers
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=embedded.pdf");

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_PDF)
                    .body(outputStream -> {
                        try{
                            testService.createPdfWithEmbeddedFile(EMBEDDING_FILE_PATH, outputStream);
                        }catch (Exception e){
                            throw new RuntimeException("Error embedding file: "+ e.getMessage(),e);
                        }
                    });
    }

@shrisheshpratik

Below is the sample code snippet that we have used to test the scenario with the latest version of the API and we could not notice any issue in the generated output:

Document doc = new Document(dataDir + "test.pdf");
String filename = "";
String source = dataDir + "test.docx";

filename = new File(source).getName();

FileSpecification fileSpec = new FileSpecification(source, "Some description");
doc.getEmbeddedFiles().add("Some place", fileSpec);

doc.save(dataDir + "aspose_attachment.pdf");

aspose_attachment.pdf (64.5 KB)

Would you kindly make sure that you are using the latest version of the API and try to use the code like above. If issue still persists, please share some steps to reproduce it so that we can further proceed accordingly.