服务器网页 文件存放,如何在不将文件存储在服务器端的情况下将PDF提供给浏览器?...

小编典典

建议您使用response.getOutputStream()而不是创建a的人FileOutputStream是正确的。例如,请参阅本书第9章中的Hello

Servlet:

public class Hello extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("application/pdf");

try {

// step 1

Document document = new Document();

// step 2

PdfWriter.getInstance(document, response.getOutputStream());

// step 3

document.open();

// step 4

document.add(new Paragraph("Hello World"));

document.add(new Paragraph(new Date().toString()));

// step 5

document.close();

} catch (DocumentException de) {

throw new IOException(de.getMessage());

}

}

}

但是,当您像这样直接发送字节时,某些浏览器会遇到问题。使用a在内存中创建文件ByteArrayOutputStream并告诉浏览器在内容标头中可以预期多少字节是更安全的:

public class PdfServlet extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

try {

// Get the text that will be added to the PDF

String text = request.getParameter("text");

if (text == null || text.trim().length() == 0) {

text = "You didn't enter any text.";

}

// step 1

Document document = new Document();

// step 2

ByteArrayOutputStream baos = new ByteArrayOutputStream();

PdfWriter.getInstance(document, baos);

// step 3

document.open();

// step 4

document.add(new Paragraph(String.format(

"You have submitted the following text using the %s method:",

request.getMethod())));

document.add(new Paragraph(text));

// step 5

document.close();

// setting some response headers

response.setHeader("Expires", "0");

response.setHeader("Cache-Control",

"must-revalidate, post-check=0, pre-check=0");

response.setHeader("Pragma", "public");

// setting the content type

response.setContentType("application/pdf");

// the contentlength

response.setContentLength(baos.size());

// write ByteArrayOutputStream to the ServletOutputStream

OutputStream os = response.getOutputStream();

baos.writeTo(os);

os.flush();

os.close();

}

catch(DocumentException e) {

throw new IOException(e.getMessage());

}

}

}

second-

edition/chapter-9#377-pdfservlet.java)。您可以在此处尝试代码:http

2020-09-16

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值