[英]How to convert a Blob object into a PDF file in Java?
我有以下情况进入Java申请。
从数据库中检索此Blob object,它表示 DB 上的 PDF 文件:
Blob blobPdf = cedolinoPdf.getAllegatoBlob();
现在我必须将它转换成一个 PDF 文件。 我该如何完成这项任务?
发件人
如果Blob是PDF的二进制表示形式,那么您要做的就是获取字节。 如果您想将PDF写入文件,则可以...
Blob blobPdf = ...;
File outputFile = new File("/tmp/blah/whatever.pdf");
FileOutputStream fout = new FileOutputStream(outputFile);
IOUtils.copy(blobPdf.getBinaryStream(), fout);
这会将您的PDF写入名为“ /tmp/blah/whatever.pdf”的文件
您可以使用ResultSet中的getBinaryStream(),然后可以根据getBinaryStream()返回的InputStream创建文件。
您的代码可能看起来像这样
Connection connection = null; Statement statement = null; ResultSet rs = null; try { Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(connectionURL, "sa", "sa"); statement = connection.createStatement(); rs = statement.executeQuery("SELECT fileName,blobFile FROM tblBlobFiles"); if (rs.next()) { String filename = rs.getString(1); Blob blob = rs.getBlob(2); InputStream is = blob.getBinaryStream(); FileOutputStream fos = new FileOutputStream("C:\\\\DownloadedFiles"+ "\\\\" + filename); int b = 0; while ((b = is.read()) != -1) { fos.write(b); } } } catch (IOException e) { e.getMessage (); e.printStackTrace(); System.out.println(e); } catch (SQLException e) { e.getMessage (); e.printStackTrace(); System.out.println(e); }
如果需要所有斑点,请对结果集进行迭代
您可以使用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();
将 Blob 转换为 PDF 并不是那么简单的任务。 我曾使用 itext.5.5.9.jar 来实现相同的目的,这是我的代码:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.