web-dev-qa-db-fra.com

Comment convertir un fichier PDF en base64 et encoder / décoder

OK, j'ai des pdf à convertir en base64 par base64encoder.

enfin, j'utilise decoder pour reconvertir au format pdf mais mon contenu est perdu.

mon code:

byte[] input_file = Files.readAllBytes(Paths.get("C:\\user\\Desktop\\dir1\\dir2\\test3.pdf"));
    byte[] encodedBytes = Base64.getEncoder().encode(input_file);

    String pdfInBase64 = new String(encodedBytes);
    String originalString = new String(Base64.getDecoder().decode(encodedBytes));

    System.out.println("originalString : " + originalString);

    FileOutputStream fos = new FileOutputStream("C:\\user\\Desktop\\dir1\\dir2\\newtest3.pdf");
    fos.write(originalString.getBytes());
    fos.flush();
    fos.close();

résultat :

Encoder: https://Pastebin.com/fnMACZzH

avant base64encode

après décodage

Merci

9
DKKs

Vous pouvez décoder une chaîne encodée en base64 et transmettre que byte[] to FileOutputStream write méthode pour résoudre ce problème.

        String filePath = "C:\\Users\\xyz\\Desktop\\";
        String originalFileName = "96172560100_copy2.pdf";
        String newFileName = "test.pdf";

        byte[] input_file = Files.readAllBytes(Paths.get(filePath+originalFileName));

        byte[] encodedBytes = Base64.getEncoder().encode(input_file);
        String encodedString =  new String(encodedBytes);
        byte[] decodedBytes = Base64.getDecoder().decode(encodedString.getBytes());

        FileOutputStream fos = new FileOutputStream(filePath+newFileName);
        fos.write(decodedBytes);
        fos.flush();
        fos.close();
11
Ajit Soman

J'ai utilisé la bibliothèque Apache Commons. La version que j'ai utilisée pour tester cet utilitaire est commons-code-1.4.jar. Il existe plusieurs utilisations de Codec Base64. C’est lors de l’appel du service Web Docusign eSignature que les fichiers joints ont été envoyés dans un format codé Base64.

import Java.io.BufferedInputStream;
import Java.io.BufferedOutputStream;
import Java.io.File;
import Java.io.FileInputStream;
import Java.io.FileOutputStream;
import Java.io.IOException;

import org.Apache.commons.codec.binary.Base64;

public class FileCodecBase64 {

    private static final boolean IS_CHUNKED = true;

    public static void main(String args[]) throws Exception {

        /* Encode a file and write the encoded output to a text file. */
        encode("C:/temp/something.pdf", "c:/temp/something-encoded.txt", IS_CHUNKED);

        /* Decode a file and write the decoded file to file system */
        decode("C:/temp/something-encoded.txt", "c:/temp/something-decoded.pdf");
    }

    /**
     * This method converts the content of a source file into Base64 encoded data and saves that to a target file.
     * If isChunked parameter is set to true, there is a hard wrap of the output  encoded text.
     */
    private static void encode(String sourceFile, String targetFile, boolean isChunked) throws Exception {

        byte[] base64EncodedData = Base64.encodeBase64(loadFileAsBytesArray(sourceFile), isChunked);

        writeByteArraysToFile(targetFile, base64EncodedData);
    }

    public static void decode(String sourceFile, String targetFile) throws Exception {

        byte[] decodedBytes = Base64.decodeBase64(loadFileAsBytesArray(sourceFile));

        writeByteArraysToFile(targetFile, decodedBytes);
    }

    /**
     * This method loads a file from file system and returns the byte array of the content.
     * 
     * @param fileName
     * @return
     * @throws Exception
     */
    public static byte[] loadFileAsBytesArray(String fileName) throws Exception {

        File file = new File(fileName);
        int length = (int) file.length();
        BufferedInputStream reader = new BufferedInputStream(new FileInputStream(file));
        byte[] bytes = new byte[length];
        reader.read(bytes, 0, length);
        reader.close();
        return bytes;

    }

    /**
     * This method writes byte array content into a file.
     * 
     * @param fileName
     * @param content
     * @throws IOException
     */
    public static void writeByteArraysToFile(String fileName, byte[] content) throws IOException {

        File file = new File(fileName);
        BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(file));
        writer.write(content);
        writer.flush();
        writer.close();

    }
}

j'espère que ce travail

2
dev_ramiz_1707