生成PDF文件

@Action("report_exportPdf")
    public String exportPdf() throws Exception{
        //查询出满足当前条件 结果数据
        List<WayBill> wayBills = wayBillService.findWayBills(model);
        //下载导出
        //设置头信息
        ServletActionContext.getResponse().setContentType("application/pdf");
        String filename = "运单数据.pdf";
        
        String agent = ServletActionContext.getRequest().getHeader("user-agent");
        filename = FileUtils.encodeDownloadFilename(filename, agent);
        ServletActionContext.getResponse().setHeader("Content-Disposition",
                "attachment;filename="+filename);
        //生成PDF文件
        Document document = new Document();
        PdfWriter.getInstance(document, ServletActionContext.getResponse().getOutputStream());
        document.open();
        //写PDF数据
        //向document生成pdf表格
        Table table = new Table(7);
        table.setWidth(80);//宽度
        table.setBorder(1);//边框
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);//水平对齐方式
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_TOP);    //垂直对齐方式
        //设置字体
        BaseFont cn = BaseFont.createFont("STSongStd-Light" , "UniGB-UCS2-H",false);
        Font font = new Font(cn,10,Font.NORMAL,Color.BLUE);
        //写表头
        table.addCell(buildCell("运单号",font));
        table.addCell(buildCell("寄件人", font));
        table.addCell(buildCell("寄件人电话", font));
        table.addCell(buildCell("寄件人地址", font));
        table.addCell(buildCell("收件人", font));
        table.addCell(buildCell("收件人电话", font));
        table.addCell(buildCell("收件人地址", font));
        // 写数据
        for (WayBill wayBill : wayBills) {
            table.addCell(buildCell(wayBill.getWayBillNum(), font));
            table.addCell(buildCell(wayBill.getSendName(), font));
            table.addCell(buildCell(wayBill.getSendMobile(), font));
            table.addCell(buildCell(wayBill.getSendAddress(), font));
            table.addCell(buildCell(wayBill.getRecName(), font));
            table.addCell(buildCell(wayBill.getRecMobile(), font));
            table.addCell(buildCell(wayBill.getRecAddress(), font));
        }
        // 将表格加入文档
        document.add(table);

        document.close();

        return NONE;
    }
    private Cell buildCell(String content, Font font)
            throws BadElementException {
        Phrase phrase = new Phrase(content, font);
        return new Cell(phrase);
    }

原文地址:https://www.cnblogs.com/lijingbo/p/7400091.html