How to convert a raw pdf file string to base64?
06:56 22 Feb 2024

I am trying to convert a basic raw pdf file string to base64. The base64 is generated correctly but when i decode it to an actual pdf file, the file can't be generated.

I have tried several other methods, tried the Charset.UTF_8 as well but nothing seems to be working.

I cannot use the actual pdf file asI get the string from another service call so it will always be a raw pdf file string

        public String get() throws CustomException, IOException {

            String testPDf = "%PDF-1.4\n" +
                "%âãÏÓ\n" +
                "1 0 obj\n" +
                "<< /Type /Catalog\n" +
                "   /Pages 2 0 R\n" +
                ">>\n" +
                "endobj\n" +
                "2 0 obj\n" +
                "<< /Type /Pages\n" +
                "   /Kids [3 0 R]\n" +
                "   /Count 1\n" +
                ">>\n" +
                "endobj\n" +
                "3 0 obj\n" +
                "<< /Type /Page\n" +
                "   /Parent 2 0 R\n" +
                "   /Resources << /Font << /F1 << /Type /Font\n" +
                "                                /Subtype /Type1\n" +
                "                                /BaseFont /Helvetica\n" +
                "                             >> >>\n" +
                "   /MediaBox [0 0 612 792]\n" +
                "   /Contents 4 0 R\n" +
                ">>\n" +
                "endobj\n" +
                "4 0 obj\n" +
                "<< /Length 55 >>\n" +
                "stream\n" +
                "BT\n" +
                "/F1 18 Tf\n" +
                "100 100 Td\n" +
                "(Hello, World!) Tj\n" +
                "ET\n" +
                "endstream\n" +
                "endobj\n" +
                "xref\n" +
                "0 5\n" +
                "0000000000 65535 f\n" +
                "0000000018 00000 n\n" +
                "0000000077 00000 n\n" +
                "0000000175 00000 n\n" +
                "0000000451 00000 n\n" +
                "trailer\n" +
                "<< /Size 5\n" +
                "   /Root 1 0 R\n" +
                ">>\n" +
                "startxref\n" +
                "561\n" +
                "%%EOF";

        testPDf = testPDf.replaceAll("\n", "");

        testPDf = toBase64(testPDf);

        return testPDf;
    }

    public static String toBase64(String str) throws UnsupportedEncodingException {

        byte[] bytes = str.getBytes("UTF-8");
        String encoded = Base64.getEncoder().encodeToString(bytes);
        return encoded;
    }

I am using an online converter to test the generatedbase64.

java pdf encoding base64