0

I am trying to save bytes[] data in a pdf and zip it up. Everytime I try, I get a blank pdf. Below is the code. Can anyone guide me what am I doing wrong?

byte[] decodedBytes = Base64.decodeBase64(contents);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("c:\\output\\asdwd.zip")));
                    //now create the entry in zip file

ZipEntry entry = new ZipEntry("asd.pdf");
zos.putNextEntry(entry);
zos.write(decodedBytes);
zos.close();    

This is what I am following

To obtain the actual PDF document, you must decode the Base64-encoded string, save it as a binary file with a “.zip” extension, and then extract the PDF file from the ZIP file.

user3509208
  • 531
  • 1
  • 5
  • 15
  • First try creating just the PDF. Once that works move on to implementing the zip. – Susmit Agrawal Aug 19 '18 at 12:26
  • Any idea how that can be created from byte data? – user3509208 Aug 19 '18 at 12:27
  • Check this: https://stackoverflow.com/a/42721500/3888766 – Fullstack Guy Aug 19 '18 at 12:27
  • Are you trying to extract the PDF? It appears the instructions are telling you that the content is already in (base64 encoded) zip format, and you must extract the PDF from that zip archive. If you wish to extract the PDF document, you don’t want to zip your data, you want to unzip it. – VGR Aug 19 '18 at 16:28
  • @VGR I think you are absolutely right. Would you have or recommend any piece of code through which i can achieve this? I have decoded the file using byte[] decodedBytes = Base64.decodeBase64(contents);. The instruction tell to save the file as binary with .zip extension. Any idea how this can be achieved? – user3509208 Aug 19 '18 at 18:46
  • Please share an example of a so encoded pdf. – mkl Aug 20 '18 at 04:49

1 Answers1

0

You don’t actually need to create a zip file. The instructions are telling you that the base64 data represents a zipped PDF, so you can unzip it in code and write the PDF file itself:

Path pdfFile = Files.createTempFile(null, ".pdf");

try (ZipInputStream zip = new ZipInputStream(
        new ByteArrayInputStream(
            Base64.getDecoder().decode(contents)))) {

    ZipEntry entry;
    while ((entry = zip.getNextEntry()) != null) {
        String name = entry.getName();
        if (name.endsWith(".pdf") || name.endsWith(".PDF")) {
            Files.copy(zip, pdfFile, StandardCopyOption.REPLACE_EXISTING);
            break;
        }
    }
}
VGR
  • 40,506
  • 4
  • 48
  • 63
  • Thanks for the code mate but the pdf being generated is blank. Any idea? – user3509208 Aug 20 '18 at 00:43
  • Maybe the PDF was not given a meaningful name in the zip archive. Try removing the `if (name.endsWith(".pdf") || name.endsWith(".PDF"))`, so the first archive entry is always used regardless of its name. – VGR Aug 20 '18 at 03:12