Chitresh Kukreja
Chitresh Kukreja

Reputation: 11

How to Store PDF Content In String Base64 format

I want to store a PDF in Base64 format before sending it to a FileOutputStream. I tried the code below. I tried using the write method of OutputStream with anonymous inner class but the content gets null.

package com.hmkcode;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.html2pdf.HtmlConverter;

public class App 
{
    public static final String HTML = "<h1>Hello</h1>"
        + "<p>This was created using iText</p>"
        + "<a href='hmkcode.com'>hmkcode.com</a>";

    public static void main( String[] args ) throws FileNotFoundException, IOException {
        HtmlConverter.convertToPdf(HTML, new FileOutputStream("string-to-pdf.pdf"));
        System.out.println( "PDF Created!" );
    }
}

Upvotes: 1

Views: 3998

Answers (1)

rhens
rhens

Reputation: 4871

You can simply use the wrap method of the java.util.Base64.Encoder class to get an OutputStream that performs Base64 encoding to anything written to it:

FileOutputStream fos = new FileOutputStream("pdf-base64.txt");
OutputStream base64os = Base64.getEncoder().wrap(fos);
HtmlConverter.convertToPdf(HTML, base64os);

Note that the documentation says to close the Base64 output stream:

It is recommended to promptly close the returned output stream after use, during which it will flush all possible leftover bytes to the underlying output stream. Closing the returned output stream will close the underlying output stream.

convertToPdf closes the output stream automatically, but if you're creating the PDF in a different way, make sure to call base64os.close().


If for some reason you want to create the PDF first and do the Base64 encoding afterwards, you can use one of the many Base64 encoding implementations out there. For example, using java.util.Base64.Encoder:

// Create PDF
ByteArrayOutputStream baos = new ByteArrayOutputStream();
HtmlConverter.convertToPdf(HTML, baos);

// Generate Base64 encoded version of PDF
byte[] base64encoded = Base64.getEncoder().encode(baos.toByteArray());

// Write Base64 data to file
FileOutputStream fos = new FileOutputStream("pdf-base64.txt");
fos.write(base64encoded);
fos.close();

Upvotes: 1

Related Questions