excel转pdf方案

今天需求说希望将导出的excel转成pdf格式,来避免用户修改文件,下面简单整理了这次修改的方案:

1 excel转pdf方式
参考示例: https://github.com/caryyu/excel2pdf.git
它的原理也是大家最直观的想法,获取excel然后将它转换成pdf,实际核心代码如下,可以看到,代码需求从excel中取值,然后再加入到pdf中,逻辑比较复杂

` protected PdfPTable toParseContent(Sheet sheet) throws BadElementException, MalformedURLException, IOException{
int rows = sheet.getPhysicalNumberOfRows();

    List<PdfPCell> cells = new ArrayList<PdfPCell>();
    float[] widths = null;
    float mw = 0;
    for (int i = 0; i < rows; i++) {
        Row row = sheet.getRow(i);
        int columns = row.getLastCellNum();

        float[] cws = new float[columns];
        for (int j = 0; j < columns; j++) {
            Cell cell = row.getCell(j);
            if (cell == null) cell = row.createCell(j);

            float cw = getPOIColumnWidth(cell);
            cws[cell.getColumnIndex()] = cw;

            cell.setCellType(Cell.CELL_TYPE_STRING);
            CellRangeAddress range = getColspanRowspanByExcel(row.getRowNum(), cell.getColumnIndex());

            int rowspan = 1;
            int colspan = 1;
            if (range != null) {
                rowspan = range.getLastRow() - range.getFirstRow() + 1;
                colspan = range.getLastColumn() - range.getFirstColumn() + 1;
            }

            PdfPCell pdfpCell = new PdfPCell();
            pdfpCell.setBackgroundColor(new BaseColor(POIUtil.getRGB(
                    cell.getCellStyle().getFillForegroundColorColor())));
            pdfpCell.setColspan(colspan);
            pdfpCell.setRowspan(rowspan);
            pdfpCell.setVerticalAlignment(getVAlignByExcel(cell.getCellStyle().getVerticalAlignment()));
            pdfpCell.setHorizontalAlignment(getHAlignByExcel(cell.getCellStyle().getAlignment()));
            pdfpCell.setPhrase(getPhrase(cell));

            if (sheet.getDefaultRowHeightInPoints() != row.getHeightInPoints()) {
                pdfpCell.setFixedHeight(this.getPixelHeight(row.getHeightInPoints()));
            }

            addBorderByExcel(pdfpCell, cell.getCellStyle());
            addImageByPOICell(pdfpCell , cell , cw);

            cells.add(pdfpCell);
            j += colspan - 1;
        }

        float rw = 0;
        for (int j = 0; j < cws.length; j++) {
            rw += cws[j];
        }
        if (rw > mw ||  mw == 0) {
            widths = cws;
            mw = rw;
        }
    }

    PdfPTable table = new PdfPTable(widths);
    table.setWidthPercentage(100);
    for (PdfPCell pdfpCell : cells) {
        table.addCell(pdfpCell);
    }
    return table;
}`

2 直接通过pdf模板生成pdf

示例文档: https://blog.csdn.net/weixin_41187876/article/details/79156969?tdsourcetag=s_pcqq_aiomsg

流程是:获取pdf模板->获取数据->生成pdf文件

这种方式感觉更直观,也少了转换操作,性能更好

3 针对我这次需求,是为了防止用户修改excel文件

其实,excel中有加密功能,一行代码就可以解决

sheet.protectSheet(UUID.randomUUID().toString());

posted @ 2020-06-11 17:04  橙木鱼  阅读(483)  评论(0编辑  收藏  举报