从MySql / Java检索和显示PDF文档

时间:2013-02-27 11:31:34

标签: java swing java-ee jdbc

我正在尝试将我的Java程序生成的PDF保存到Mysql数据库中,并尝试检索/显示相同的Java程序。以下代码具有我迄今为止所做的工作,

public class Save_PDFimage extends javax.swing.JFrame {
    private ImageIcon format = null;
    Connection conn = null;
    ResultSet rs=null;
    PreparedStatement pst=null;
    //String filename = "C:\\Users\\***\\Desktop\\n.png";
    String filename = "C:\\Users\\***\\Desktop\\in.pdf";
    int s = 0;
    byte[] person_image = null;

private void Save_DBActionPerformed(java.awt.event.ActionEvent evt) {
    try {
    File image = new File(filename);
    FileImageInputStream FIS = new FileImageInputStream(image);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    for(int readNum; (readNum=FIS.read(buf))!=-1;) {
    bos.write(buf,0,readNum);
    }
    person_image = bos.toByteArray();
    } catch(Exception e)
    {
    JOptionPane.showMessageDialog(null, e);
    }

    try {
    String sql = "Insert into invoices (Pdfs, Invoice_no_R) values(?,?)";
    String i= "1";
    pst = conn.prepareStatement(sql);
    pst.setBytes(1, person_image);
    pst.setString(2, i);
    pst.execute();
    } catch(Exception e)
    {
    JOptionPane.showMessageDialog(null, e);
    }
    }

// Code for displaying the retrieved PDF in a jLabel

   private void Show_imageActionPerformed(java.awt.event.ActionEvent evt) {
    try {
        String sql = "select Pdfs from invoices where Invoice_no_R = 1";
        pst = conn.prepareStatement(sql);
        rs = pst.executeQuery();

        if (rs.next())
        {
        byte[] Imagedata = rs.getBytes("Pdfs");
        format = new ImageIcon(Imagedata);
        jLabel1.setIcon(format);
        }
    } catch(Exception e ) {
        JOptionPane.showMessageDialog(null, e);
        e.printStackTrace();
    } }

我能够保存PDF但是程序在检索后不显示图像,同样的逻辑适用于PNG / JPG文件。

请帮忙......

拉​​梅什

1 个答案:

答案 0 :(得分:0)

pdf不是图像格式 - 它是二进制格式。 您无法将其设置为imageicon的图标。