servlet中如何生成pdf呢?

乔欣 Servlet 发布时间:2022-12-17 21:34:45 阅读数:18086 1
下文笔者讲述在servlet开发中--如何直接在后台生成pdf,然后发送到前端呢?

pdf简介

pdf是一种电脑上常用的阅读格式
也是我们web打印常采用的格式,那么servlet中如何直接生成pdf呢?
下文笔者将一一道来,如下所示
实现思路:
    使用itext中的PDfWrite生成pdf
	然后使用流的方式发送到前端浏览器中即可
例:
public class PdfServlet extends HttpServlet {

    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        try {
            // 获取生成pdf所需的文本
            String text = request.getParameter("text");
            if (text == null || text.trim().length() == 0) {
                 text = "pdf中没有任何文本信息";
            }
            // 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());
        }
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/Servlet/202212/281.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者