我希望java代码在浏览器上查看pdf文件而不下载它们

时间:2015-03-07 10:13:29

标签: java pdf

我正在搜索java代码,无需下载即可在浏览器上查看pdf文件。这些文件将通过数据库插入。欢迎帮助。

1 个答案:

答案 0 :(得分:1)

您需要使用servlet来执行此操作:

import java.io.IOException;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

public class viewPDF extends HttpServlet {

    public void doGet(HttpServletRequest request, 
            HttpServletResponse response)
    throws ServletException, IOException {
        OutputStream out = null;
        DB1 db = new DB1();
        Connection conn=db.dbConnect(
                "jdbc:jtds:sqlserver://localhost:1433/smpp","sa","");

        try {

            response.setContentType("application/pdf");
            out = response.getOutputStream();
            byte[] b = db.getPDFData(conn);
            out.write(b,0,b.length);
            out.close();
        } catch (Exception e) {
            throw new ServletException(
                    "Exception in Excel Sample Servlet", e);
        } finally {
            if (out != null)
                out.close();
        }
    }

    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {
        doGet(request, response);
    }
}

在此处查看更多信息以及在浏览器中使用数据库中的PDF的完整工作示例:java-tips