'How to convert a Blob object into a PDF file in Java?
I have the following situation into a Java application.
From the database a retrieve this Blob object that is the representation of a PDF file on the DB:
Blob blobPdf = cedolinoPdf.getAllegatoBlob();
Now I have to convert it into a PDF file. How can I do this task?
Tnx
Solution 1:[1]
If the Blob is the binary representation of a PDF, all you need to do is get the bytes. If you wanted to write the PDF to a file, you could do...
Blob blobPdf = ...;
File outputFile = new File("/tmp/blah/whatever.pdf");
FileOutputStream fout = new FileOutputStream(outputFile);
IOUtils.copy(blobPdf.getBinaryStream(), fout);
This should write your PDF to a file called "/tmp/blah/whatever.pdf"
Solution 2:[2]
you can use Java NIO
InputStream fileBolb = rs.getBinaryStream("columnName");
ReadableByteChannel rbc = Channels.newChannel(fileBolb );
FileOutputStream fos = new FileOutputStream(filePath + fname);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
Solution 3:[3]
Converting Blob into PDF is not that much straight forward task. I had used itext.5.5.9.jar to achieve same, here is my code:
public static void blobToPDF(String[] args) throws IOException {
Blob blobPdf = ....;
com.itextpdf.kernel.pdf.PdfReader newreader = null;
try (InputStream targetStream = blobPdf.getBinaryStream()) {
newreader = new com.itextpdf.kernel.pdf.PdfReader(targetStream);
System.out.println("Reading PDF using com.itextpdf.kernel.pdf.PdfReader...");
System.out.println("PDF read success with kernel package ");
System.out.println("PDF length = " + newreader.getFileLength());
} catch (InvalidPdfException | FileNotFoundException | SQLException ipe) {
ipe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (newreader != null)
newreader.close();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Gaurab Pradhan |
| Solution 3 |
