java 浏览器 pdf_使用Java Servlet在浏览器中显示Pdf

这篇博客探讨了如何在浏览器中通过Java Servlet显示PDF文件。作者遇到的问题是,他们只有文件输入流,而没有PDF路径。目前的实现通过Ajax请求调用`showPdf`方法,该方法将PDF文件转换为字节数组输出流并写入响应流。然而,显示的内容并非PDF的正常视图,而是包含了PDF的原始字节。作者寻求解决方案以正确地在浏览器中呈现PDF。
摘要由CSDN通过智能技术生成

我的申请中有pdf文件。我需要在浏览器中显示pdf。我正在将文件作为fileInputStream读取,我需要在浏览器中与我的应用程序一起显示pdf。但我没有pdf路径,我有文件流。

请给我一些建议和例子

我已经使用ajax显示pdf,正在使用call_method()javascript

ajax请求方法来调用showPdf操作,在showpdf操作中,只是将pdf文件转换为ByteArrayOutputStream并将结果写入输出流中。但是它显示了下面提到的结果。

结果在JSP中 :

%PDF-1.4% 1 endstream endobj 4 0 obj <>>> / MediaBox [0 0 595 842] >> endobj 1

0 obj <> endobj 3 0 obj <> endobj 5 0 obj <> endobj 6 0 obj <> endobj xref 0 7

0000000000 65535 f 0000000389 00000 n 0000000015 00000 n 0000000477 00000 n

0000000232 00000 n 0000000540 00000 n 0000000585 00000 n拖车<<

142354f5ebefd65d6aacd33a7cb2b4ab>] / Info 6 0 R / Size 7 >> startxref 707 %%

EOF

请给一些建议。

Javascript Ajax:

call_method();

function call_method(){

Ext.Ajax.request({

waitMsg: 'Saving changes...',

url:'test.action?method=showPdf',

params : { },

failure:function(response,options){

},

success:function(response,options){

$("#pdf_content").show();

$("#pdf_content").html(response.responseText);

$("#pdf_content").show('slow');

}

});

}

Java方法:

public String showPdf() throws IOException {

getResponse().setContentType("application/pdf");

getResponse().setHeader("Content-disposition","inline; filename=automatic_start.pdf" );

ByteArrayOutputStream baos = getByteArrayOutputStream();

getResponse().setContentLength(baos.size());

ServletOutputStream sos;

sos = getResponse().getOutputStream();

baos.writeTo(sos);

sos.flush();

return null;

}

private ByteArrayOutputStream getByteArrayOutputStream() throws IOException {

String filePath = "/homefolder/";

String folderPath=filePath+"1122/automatic_start.pdf";

File file = new File(folderPath);

FileInputStream fis = new FileInputStream(file);

ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte[] buf = new byte[256];

try {

for (int readNum; (readNum = fis.read(buf)) != -1;) {

bos.write(buf, 0, readNum); //no doubt here is 0

//Writes len bytes from the specified byte array starting at offset off to this byte array output stream.

System.out.println("read " + readNum + " bytes,");

}

} catch (IOException ex) {

ex.printStackTrace();

}

return bos;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值