Search code examples
javajava-iopdfrenderer

Need help with pdf-renderer


I'm using PDF-Renderer to view PDF files within my java application. It's working perfectly for normal PDF files.

However, i want the application to be able to display encrypted PDF files. The ecrypted file will be decrypted with CipherInputStream, but i do not want to save the decrypted data on disk. Am trying to figure a way i can pass the decryted data from CipherInputStream to the PDFFile constructor without having to write the decryted data to file.

I will also appreciate if someone can help with a link to PDF-Renderer tutorial, so that i can read up more on it.

Thanks.


Solution

  • Try the following class:

    import com.sun.pdfview.PDFFile;
    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.ByteBuffer;
    import java.nio.channels.Channels;
    import java.nio.channels.ReadableByteChannel;
    
    public class PDFFileUtility {
    private static final int READ_BLOCK = 8192;
    
    public static PDFFile getPDFFile(InputStream in) throws IOException {
       ReadableByteChannel bc = Channels.newChannel(in);
       ByteBuffer bb = ByteBuffer.allocate(READ_BLOCK);
        while (bc.read(bb) != -1) {
            bb = resizeBuffer(bb); //get new buffer for read
        }
       return new PDFFile(bb);
    
    }
    
     private static ByteBuffer resizeBuffer(ByteBuffer in) {
       ByteBuffer result = in;
       if (in.remaining() < READ_BLOCK) {
        result = ByteBuffer.allocate(in.capacity() * 2);
        in.flip();
        result.put(in);
       }
       return result;
    }
    }
    

    So call:

    PDFFileUtility.getPDFFile(myCipherInputStream);