使用IText生成PDF,條形碼,通過url在線預覽

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>

效果圖

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章