使用IText生成PDF,条形码,通过url在线预览

博客介绍了使用iText生成PDF和条形码,并可通过url在线预览。给出了iText英文API文档链接,还提及PdfClient、PdfUtil、Maven等相关内容,同时提醒导包时要注意使用com.itextpdf.text而非com.lowagie.text,最后展示了效果图。

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

IText文档(英文API文档)

https://itextsupport.com/apidocs/iText5/5.5.13/
https://www.coderanch.com/how-to/javadoc/itext-2.1.7/com/lowagie/text/pdf/Barcode128.html

在线预览

@Override
public void printPdf(String orderId){
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletResponse response = requestAttributes.getResponse();

    try {
        Document document = new Document();
        ServletOutputStream out = response.getOutputStream();
        // 文件输出流指向PDF文件
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, bao);
        
        // 查询SKU信息
        List<Order> orderList = orderRepository.findByOrgCode(orderId);
        if (CollectionUtils.isEmpty(orderList)) {
            logger.error("生成PDF失败 --> orderId={}",orderId);
            throw new Exception("生成PDF失败,未查询到数据!");
        }
        List<OrderEntry> orderEntryList = orderEntryRepository.findByOrderId(orderList.get(0).getId());
        // 编辑PDF
        PdfClient.createPdf(writer, document, orderEntryList, orderId);

        // 设置页面编码格式
        response.setContentType("application/pdf");
        response.setContentLength(bao.size());
        response.setHeader("Content-Disposition", "inline;filename=" + new String((PdfConstant.FILE_NAME + DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN)).getBytes(), "ISO-8859-1") + ".pdf");
        // 实现页面预览PDF
        bao.writeTo(out);
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("导出PDF出错 --> e={}",e.getMessage());
    }
}

PdfClient

public static void createPdf(PdfWriter writer, Document document, List<OrderEntry> orderEntryList, String orderId) throws Exception {
    // 打开文档
    document.open();

    Paragraph paragraph = new Paragraph("合作伙伴系统", PdfUtil.setFont(12f, BaseColor.GRAY, false));
    // 居中
    paragraph.setAlignment(Element.ALIGN_CENTER);
    document.add(paragraph);

    PdfPTable table = PdfUtil.setTable(3, 300, 40f, 50f, new float[]{290, 70, 50});

    PdfUtil.setCell(table, BaseColor.BLACK, false, 60, false,
            PdfUtil.setSpace("中远", 3, 1, 15, 0, PdfUtil.setFont(20f, BaseColor.BLACK, false)));

    // 条形码
    PdfUtil.setBarcodeCell(table, 20, 150, 3, 100,
            PdfUtil.createBarcode(writer, orderId, true));

    PdfUtil.setCell(table, BaseColor.BLACK, false, 60, false,
            PdfUtil.setSpace("订单号:" + orderId, 3, 1, 15, 0, PdfUtil.setFont(17f, BaseColor.GRAY, false)));

    Font font = PdfUtil.setFont(16f, BaseColor.BLACK, false);
    PdfUtil.setCell(table, BaseColor.GRAY, false, 60, false,
            PdfUtil.setSpace("商品名称", 1, 1, 10, 0, font));

    PdfUtil.setCell(table, BaseColor.GRAY, true, 60, false,
            PdfUtil.setSpace("商品规格", 1, 1, 0, 0, font));

    PdfUtil.setCell(table, BaseColor.GRAY, true, 60, false,
            PdfUtil.setSpace("件数", 1, 1, 0, 0, font));

    // 插入SKU信息
    orderEntryList.forEach(orderEntry -> {
        Font fontSku = PdfUtil.setFont(16f, BaseColor.GRAY, false);
        // 商品名称
        PdfUtil.setCell(table, BaseColor.GRAY, false, 60, false,
                PdfUtil.setSpace(orderEntry.getProduct().getName(), 1, 1, 10, 0, fontSku));

        // 商品规格
        PdfUtil.setCell(table, BaseColor.GRAY, true, 60, false,
                PdfUtil.setSpace(orderEntry.getProduct().getSpecName(), 1, 1, 0, 0, fontSku));

        // 商品件数
        PdfUtil.setCell(table, BaseColor.GRAY, true, 60, false,
                PdfUtil.setSpace(String.valueOf(orderEntry.getQuantity()), 1, 1, 0, 0, fontSku));
    });

    document.add(table);
    // 关闭文档
    document.close();
}

PdfUtil

public class PdfUtil {
    private static Logger logger = LoggerFactory.getLogger(PdfUtil.class);

    /**
     * 设置字体
     *
     * @param fontsize
     * @param color
     * @param isBold
     * @return
     */
    public static Font setFont(Float fontsize, BaseColor color, Boolean isBold) {
        Font font = new Font();
        try {
            //中文字体,解决中文不能显示问题
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            font = new Font(baseFont, fontsize, isBold ? Font.BOLD : Font.NORMAL, color);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("PdfUtil.setFont 设置字体出错  e={}", e);
        }
        return font;
    }

    /**
     * 设置Table
     *
     * @param numLine   列数
     * @param width     表格的宽度
     * @param upWidth   表格上面空白宽度
     * @param downWidth 表格下面空白宽度
     * @param floats    每列分别设置宽度
     * @return
     */
    public static PdfPTable setTable(int numLine, int width, float upWidth, float downWidth, float[] floats) {
        // 添加表格,3列
        PdfPTable table = new PdfPTable(numLine);
        // 设置表格宽度比例为%100
        table.setWidthPercentage(100);
        // 设置表格的宽度
        table.setTotalWidth(width);
        // 也可以每列分别设置宽度
        try {
            table.setTotalWidth(floats);
        } catch (DocumentException e) {
            e.printStackTrace();
            logger.error("PdfUtil.setTable 设置table出错  e={}", e);
        }
        // 锁住宽度
        table.setLockedWidth(true);
        // 设置表格上面空白宽度
        table.setSpacingBefore(upWidth);
        // 设置表格下面空白宽度
        table.setSpacingAfter(downWidth);
        // 设置表格默认为无边框
        table.getDefaultCell().setBorder(0);
        return table;
    }

    /**
     * 设置表格左右边距
     *
     * @param msg     表格内容
     * @param lineNum 表格占几列
     * @param lineNum 表格占几行
     * @param left
     * @param right
     * @param font
     * @return
     */
    public static PdfPCell setSpace(String msg, int lineNum, int rowNum, int left, int right, Font font) {
        // 字体样式
        PdfPCell cell = null;
        if (font == null) {
            cell = new PdfPCell(new Paragraph(msg));
        } else {
            cell = new PdfPCell(new Paragraph(msg, font));
        }
        // 设置行数
        cell.setColspan(lineNum);
        cell.setRowspan(rowNum);
        if (left > 0) {
            // 左边距
            cell.setPaddingLeft(left);
        }
        if (right > 0) {
            // 右边距
            cell.setPaddingRight(right);
        }
        return cell;
    }

    /**
     * 表格设置
     *
     * @param table
     * @param borderColor 边框颜色
     * @param center      居中
     * @param height      高度
     * @param border      无边框
     * @param cell
     * @return
     */
    public static void setCell(PdfPTable table, BaseColor borderColor, Boolean center, int height, Boolean border, PdfPCell cell) {
        // 左右居中
        if (center) {
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        }
        // 无边框
        if (border) {
            cell.setBorder(Rectangle.NO_BORDER);
        }
        // 边框颜色
        cell.setBorderColor(borderColor);
        // 上下居中
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        // 高度
        cell.setFixedHeight(height);
        table.addCell(cell);
    }

    /**
     * 创建条形码
     *
     * @param writer
     * @param barcode  条形码(数字)
     * @param hidnCode 是否隐藏条形码(数字)
     * @return
     */
    public static Image createBarcode(PdfWriter writer, String barcode, Boolean hidnCode) {
        Barcode128 code128 = new Barcode128();
        code128.setCode(barcode);
        // 增加一个条形码到表格
        code128.setCodeType(Barcode128.CODE128);
        // 隐藏文字
        if (hidnCode) {
            code128.setFont(null);
        }
        // 生成条形码图片
        PdfContentByte cb = writer.getDirectContent();
        return code128.createImageWithBarcode(cb, null, null);
    }

    /**
     * 表格添加条形码图片
     *
     * @param table
     * @param lineNum      表格占几列 setRowspan : 设置行
     * @param height       左边距
     * @param height       右边距
     * @param height       高度
     * @param code128Image 条形码图片
     * @return
     */
    public static void setBarcodeCell(PdfPTable table, int left, int right, int lineNum, int height, Image code128Image) {
        // 加入到表格
        PdfPCell cell = new PdfPCell(code128Image, true);
        // 设置左右边距
        if (left > 0) {
            // 左边距
            cell.setPaddingLeft(left);
        }
        if (right > 0) {
            // 右边距
            cell.setPaddingRight(right);
        }
        // 设置行数
        cell.setColspan(lineNum);
        // 边框颜色
        cell.setBorderColor(BaseColor.BLACK);
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        // 高度
        cell.setFixedHeight(height);
        table.addCell(cell);
    }
}

Maven

注意:导包的时候看清楚是(com.itextpdf.text),不是这个(com.lowagie.text)

	<!--itext-->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.13</version>
    </dependency>
    <!--这个是解决中文不显示的-->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext-asian</artifactId>
        <version>5.2.0</version>
    </dependency>

效果图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值