springBoot基于itext实现pdf打印

本文介绍了一种使用iText库在Spring MVC框架下生成带有详细采购信息的PDF文档的方法。通过示例代码展示了如何从数据库获取采购订单数据,并将其转换为PDF格式,包括设置页面布局、表格样式和中文字符显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom:

        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.0.6</version>
        </dependency>

 

控制器Controller

 @RequestMapping(value = "/purchase/order/print", method = RequestMethod.GET)
    public ModelAndView printInvoice(@RequestParam Long id) throws IOException {
        List<Map> list = purchaseOrderService.getList(id);
        Map<String, Object> model = new HashMap<>();
        model.put("sheet", list);
        model.put("row", 8);
        String[] title = new String[]{
                "商品条码","商品名称", "规格/单位", "进价/元", "折扣", "采购数量",
                "进货金额/元"
        };
        model.put("titles", title);
        return new ModelAndView(new ViewPDF(), model);
    }

 

 

ViewPDF文件:

/**
 * @作者:huangliang
 * @时间:2020-03-16 15:35
 * @注释:ViewPDF
 */
public class ViewPDF extends AbstractPdfView {
    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = new java.util.Date().getTime() + "_order.pdf";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "filename=" + new String(fileName.getBytes(), "iso8859-1"));
        List<Map> products = (List<Map>) model.get("sheet");
        PdfUtil pdfUtil = new PdfUtil();
        int row = (int) model.get("row");
        String[] title = (String[]) model.get("titles");
        pdfUtil.createPDF(document, writer, products, row,title);
    }
}

如果不想要这种直接在浏览器中预览的效果,而是直接下载文件的话就把response.setHeader()方法里面的参数改成下面的,相当于加了一个attachment,以附件形式下载

response.setHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(), "iso8859-1"));
PdfUtil类:

/**
 * @作者:huangliang
 * @时间:2020-03-16 15:40
 * @注释:PdfUtil
 */
public class PdfUtil {
    public void createPDF(Document document, PdfWriter writer, List<Map> products, int row, String[] titles) throws IOException {
        try {
            document.setPageSize(PageSize.A4.rotate());//设置横向打印
            document.addTitle("采购订单");
            document.addAuthor("huangliang");
            document.addSubject("product sheet.");
            document.addKeywords("product.");
            document.open();
            PdfPTable table = createPurchaseOrderTable(products, row, titles);
            document.add(table);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }

    public static PdfPTable createPurchaseOrderTable(List<Map> products, int row, String[] titles) throws IOException, DocumentException {
        PdfPTable table = new PdfPTable(row);//生成*列表格
        table.setWidthPercentage(105);

        PdfPCell cell;
        int size = 20;
        ClassPathResource resource = new ClassPathResource("static/report" + File.separator + "wryh.ttf");
        InputStream inputStream = resource.getInputStream();
        byte[] st1 = new byte[inputStream.available()];
        inputStream.read(st1);
        BaseFont baseFont = BaseFont.createFont("wryh.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED, BaseFont.NOT_CACHED,
                st1, st1);
        Font font = new Font(baseFont);
            //服务器上改成下面这种
           //BaseFont baseFont = BaseFont.createFont(new ClassPathResource("/static/report/wryh.ttf").getPath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
       // Font font = new Font(baseFont);


        PdfPCell title = new PdfPCell(new Phrase("采购订单", font));
        title.setColspan(row);//设置所占列数
        title.setFixedHeight(size * 2);//设置高度
        title.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
        title.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
        table.addCell(title);

        PdfPCell er1 = new PdfPCell(new Phrase("订单编号", font));
        er1.setColspan(2);//设置所占列数
        er1.setFixedHeight(size * 2);//设置高度
        er1.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
        er1.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
        table.addCell(er1);
        PdfPCell er2 = new PdfPCell(new Phrase("CG202003110004", font));
        er2.setColspan(2);//设置所占列数
        er2.setFixedHeight(size * 2);//设置高度
        er2.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
        er2.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
        table.addCell(er2);
        PdfPCell er3 = new PdfPCell(new Phrase("订单总金额", font));
        er3.setColspan(2);//设置所占列数
        er3.setFixedHeight(size * 2);//设置高度
        er3.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
        er3.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
        table.addCell(er3);
        PdfPCell er4 = new PdfPCell(new Phrase("50000", font));
        er4.setColspan(2);//设置所占列数
        er4.setFixedHeight(size * 2);//设置高度
        er4.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
        er4.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
        table.addCell(er4);

        addRow(table,font);



        for(String str:titles){

            cell = new PdfPCell(new Phrase(str, font));
            cell.setFixedHeight(size);
            if("商品名称".equals(str)){
                cell.setColspan(2);
            }
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
            table.addCell(cell);
        }

        for (int i = 0; i < products.size(); i++) {
            cell = new PdfPCell(new Phrase(products.get(i).get("goodsCode").toString(), font));
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(products.get(i).get("goodsName").toString(), font));
            cell.setColspan(2);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(products.get(i).get("goodsSpecifications")+"/"+products.get(i).get("goodsUnit"), font));
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(products.get(i).get("goodsOnMoney").toString(), font));
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(products.get(i).get("discount")+"%", font));
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(products.get(i).get("buyNumber").toString(), font));
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(products.get(i).get("totalMoney").toString(), font));
            cell.setFixedHeight(size);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
            table.addCell(cell);
        }
        return table;
    }

    private static void addRow(PdfPTable table,Font font) {
        PdfPCell er1 = new PdfPCell(new Phrase("制单日期", font));
        er1.setColspan(2);//设置所占列数
        er1.setFixedHeight(30);//设置高度
        er1.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
        er1.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
        table.addCell(er1);
        PdfPCell er2 = new PdfPCell(new Phrase(DateUtil.getNow(), font));
        er2.setColspan(2);//设置所占列数
        er2.setFixedHeight(30);//设置高度
        er2.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
        er2.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
        table.addCell(er2);
        PdfPCell er3 = new PdfPCell(new Phrase("供应商", font));
        er3.setColspan(2);//设置所占列数
        er3.setFixedHeight(30);//设置高度
        er3.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
        er3.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
        table.addCell(er3);
        PdfPCell er4 = new PdfPCell(new Phrase("四川新希望集团", font));
        er4.setColspan(2);//设置所占列数
        er4.setFixedHeight(30);//设置高度
        er4.setHorizontalAlignment(Element.ALIGN_CENTER);//设置水平居中
        er4.setVerticalAlignment(Element.ALIGN_MIDDLE);//设置垂直居中
        table.addCell(er4);
    }

}

wryh.ttf 文件为字体文件(微软雅黑),需要的可以留言.

 

效果图:

 

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值