从Java Sevlet嵌入PDF数据

时间:2016-08-18 17:44:56

标签: javascript java pdf embed

我有一个包含PDF数据的数据库。我已成功调用该数据并使用Java将其写入我的硬盘驱动器上的PDF文件。现在,我需要将该数据发送到Web客户端,以便将其嵌入到HTML中。我已经在这个主题上发现了很多不同的帖子,实际上有几十个,但它们都有微妙的变化(不同的编码语言,试图在新窗口中打开pdf,不同的数据类型)这个主题让我仍然感到困惑。

这是我的Java代码:

package fullView;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet(name = "GetDocuments", urlPatterns = {"/GetDocuments"})
public class GetDocuments extends HttpServlet {


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement prst = null;

    String connUrl = "Connection data omitted";


    String sql = "select * from Table where type LIKE 'application/pdf%' and id = '5'";


    try{
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        conn = DriverManager.getConnection(connUrl);
        prst = conn.prepareStatement(sql);

        rs = prst.executeQuery();
        File[] files;
        while(rs.next()){
            byte[] arr = rs.getBytes("data");
            response.setHeader("Content-Type", "application/pdf");
            response.setHeader("Content-Length", String.valueOf(arr.length));
            response.setHeader("Content-Disposition", "inline; filename=\"something.pdf\"");
            response.getOutputStream().write(arr);
            response.getOutputStream().close();
        }
    }catch(Exception e){
        String error = e.toString();
        error = "The Error is: " + error;
        error = " " + error;

    }

}


public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

有一个名为&#34; docHolder&#34;我想嵌入pdf。这是我试图制作这个问题的几十种方法中的最新一种

function embedFile(){
            $.get("GetDocuments?ER=ER1471378280115", function(responseText){                    
                 responseText = b64EncodeUnicode(responseText);  
                 var String = "<object data='data:application/pdf;base64," + responseText + "' type='application/pdf' width='700px%' height='100%'></object>";                     
                 $("#docHolder").append(String);
            });
        }

我回到了什么&#34; responseText&#34;是&#34;%PDF1.4&#34;字符串的类型。此代码确实呈现PDF,但它是许多空白页。我通过&#34;写入磁盘&#34;确认数据不仅包含空白页面。方法

1 个答案:

答案 0 :(得分:0)

您是否尝试在服务器上将内容类型设置为application / pdf。

response.setHeader("Content-Type", "application/pdf");

而不是

response.setHeader("Content-Type", "Your staffs content type");

我不知道您在javascript中使用的框架,但是,他们可能会使用http标头中的内容类型来确定文档类型。

我创建了一个简单的测试用例来帮助您

@Test
public void test_servlet() throws ServletException, IOException,  URISyntaxException{

    GetDocuments servlet = new GetDocuments();
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    ServletOutputStream os = new ServletOutputStream() {

        @Override
        public void write(byte[] b) throws IOException {
            System.out.println("Inside my stream");
            Files.write(Paths.get("MyFile.pdf"), b, StandardOpenOption.CREATE_NEW);

        }

        @Override
        public void write(int b) throws IOException {
            // TODO Auto-generated method stub

        }

        @Override
        public void setWriteListener(WriteListener arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public boolean isReady() {
            return true;
        }
    };


    Mockito.when(response.getOutputStream()).thenReturn(os);


    servlet.doGet(request, response);

}

运行它,你的数据将写在MyFile.pdf中,如果MyFile.pdf看起来也是空白页面,这意味着它是一个数据问题。

以下是我使用的依赖项

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>1.10.19</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>