java生成pdf文件

1、首先工程中增加mvn相关jar:

<!--pdf生成jar包-->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.4.2</version>
</dependency>

2、编写测试用例

package com.zdnst.test;
import java.io.File;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.zdnst.common.utils.FileStorageUtils;


public class BasePDFWrite {

    Document document = null;// 建立一个Document对象
    private static Font headFont ;
    private static Font keyFont ;
    private static Font textfont_H ;
    private static Font textfont_B ;
    int maxWidth = 520;

    static{
        BaseFont bfChinese_H;
        try {
            /**
             * 新建一个字体,iText的方法 STSongStd-Light 是字体,在iTextAsian.jar 中以property为后缀
             * UniGB-UCS2-H 是编码,在iTextAsian.jar 中以cmap为后缀 H 代表文字版式是 横版, 相应的 V 代表竖版
             */
            bfChinese_H = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);

            headFont = new Font(bfChinese_H, 10, Font.NORMAL);
            keyFont = new Font(bfChinese_H, 18, Font.BOLD);
            textfont_H = new Font(bfChinese_H, 10, Font.NORMAL);
            textfont_B = new Font(bfChinese_H, 12, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置页面属性
     * @param file
     */
    public BasePDFWrite(File file) {

        //自定义纸张
        Rectangle rectPageSize = new Rectangle(350, 620);

        // 定义A4页面大小
        //Rectangle rectPageSize = new Rectangle(PageSize.A4);
        rectPageSize = rectPageSize.rotate();// 加上这句可以实现页面的横置
        document = new Document(rectPageSize,10, 150, 10, 40);

        try {
            PdfWriter.getInstance(document,new FileOutputStream(file));
            document.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 建表格(以列的数量建)
     * @param colNumber
     * @return
     */
    public PdfPTable createTable(int colNumber){
        PdfPTable table = new PdfPTable(colNumber);
        try{
            //table.setTotalWidth(maxWidth);
            //table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
            table.setSpacingBefore(10);
            table.setWidthPercentage(100);
        }catch(Exception e){
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 建表格(以列的宽度比建)
     * @param widths
     * @return
     */
    public PdfPTable createTable(float[] widths){
        PdfPTable table = new PdfPTable(widths);
        try{
            //table.setTotalWidth(maxWidth);
            //table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
            table.setSpacingBefore(10);
            table.setWidthPercentage(100);
        }catch(Exception e){
            e.printStackTrace();
        }
        return table;
    }


    /**
     * 表格中单元格
     * @param value
     * @param font
     * @param align
     * @return
     */
    public PdfPCell createCell(String value,Font font,int align){
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value,font));
        return cell;
    }

    /**
     * 表格中单元格
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param rowspan
     * @return
     */
    public PdfPCell createCell(String value,Font font,int align_v,int align_h,int colspan,int rowspan){
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(align_v);
        cell.setHorizontalAlignment(align_h);
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        cell.setPhrase(new Phrase(value,font));
        return cell;
    }

    /**
     * 建短语
     * @param value
     * @param font
     * @return
     */
    public Phrase createPhrase(String value,Font font){
        Phrase phrase = new Phrase();
        phrase.add(value);
        phrase.setFont(font);
        return phrase;
    }

    /**
     * 建段落
     * @param value
     * @param font
     * @param align
     * @return
     */
    public Paragraph createParagraph(String value,Font font,int align){
        Paragraph paragraph = new Paragraph();
        paragraph.add(new Phrase(value,font));
        paragraph.setAlignment(align);
        return paragraph;
    }


    public void generatePDF() throws Exception{

        //页头信息
        document.add(createParagraph("【XXXX有限公司】",headFont,Element.ALIGN_LEFT));
        document.add(createParagraph("签  购  单",keyFont,Element.ALIGN_CENTER));
        document.add(createParagraph("编号:XD201602000003",headFont,Element.ALIGN_RIGHT));

        //表格信息
        float[] widths = {4f,10f,10f,20f,15f,8f,11f,12f,10f};
        PdfPTable table = createTable(widths);

        table.addCell(createCell("顾客信息", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,4));

        table.addCell(createCell("顾客名称", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1));
        table.addCell(createCell("XXXX有限公司", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,6,1));

        table.addCell(createCell("编码/税号", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1));
        table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,6,1));

        table.addCell(createCell("联系地址", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1));
        table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,6,1));

        table.addCell(createCell("采购经办人", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,2,1));
        table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("经办人电话", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1));
        table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1));
        table.addCell(createCell("经办人手机", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1));
        table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));


        table.addCell(createCell("产品订购清单", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,8));

        table.addCell(createCell("序号", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1));
        table.addCell(createCell("产品信息", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,2,1));
        table.addCell(createCell("规格型号", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1));
        table.addCell(createCell("单位", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1));
        table.addCell(createCell("单价", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1));
        table.addCell(createCell("数量", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1));
        table.addCell(createCell("小计", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1));

        table.addCell(createCell("1", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("塑料纸", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1));
        table.addCell(createCell("小号", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("个", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("400", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));

        table.addCell(createCell("2", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("塑料纸", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1));
        table.addCell(createCell("小号", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("个", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("400", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));

        table.addCell(createCell("3", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("塑料纸", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1));
        table.addCell(createCell("小号", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("个", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("400", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));



        table.addCell(createCell("4", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("合计", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1));
        table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("60", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));
        table.addCell(createCell("1200", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1));


        table.addCell(createCell("合计金额(元)", textfont_B,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,3,1));
        table.addCell(createCell("壹仟俩佰元", textfont_B,Element.ALIGN_MIDDLE, Element.ALIGN_RIGHT,6,1));


        table.addCell(createCell("顾客确认", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,3));

        table.addCell(createCell("注:本人已充分了解订购产品的功能用途,是根据实际需要自愿购买的。", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,8,1));

        table.addCell(createCell("采购经办人签字:", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,6,1));
        table.addCell(createCell("盖章:", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1));

        table.addCell(createCell("签字日期", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,8,1));

        document.add(table);
        document.close();
    }

    public static void main(String[] args) throws Exception {
        String filePath = FileStorageUtils.getTempPath();
        File file = new File(filePath+"tee.pdf");

        file.createNewFile();
        new BasePDFWrite(file).generatePDF();
    }
}

3、路径文件

package com.zdnst.common.utils;

import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import com.zdnst.common.file.storage.FileStorage;
import com.zdnst.common.file.storage.FileStorageFactory;
import com.zdnst.common.infra.constants.BaseCode;
import com.zdnst.common.infra.exception.ZdnstException;
import com.zdnst.common.infra.mangodb.MongoDb;
import com.zdnst.common.infra.utils.Assert;
import com.zdnst.common.infra.utils.ConfigUtils;
import com.zdnst.common.infra.utils.FileUtils;
import com.zdnst.common.infra.utils.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.regex.Pattern;

/**
 * 文件服务工具类
 * Created by kaiqiang.wu on 2016/4/25.
 */
public class FileStorageUtils {

    private static Logger logger = LoggerFactory.getLogger(FileStorageUtils.class);

    /**
     * 获取临时文件存储路径 /${ClassPath}/files/
     * @return
     * @throws Exception
     */
    public static String getTempPath() throws Exception {
        // 获取文件需要上传到的路径
        String tempPath = ConfigUtils.getInstance().getClassPath() + "files/";
        FileUtils.forceMkdir(new File(tempPath));
        return tempPath;
    }

    /**
     * 得到FileStorage实例
     * @return
     */
    public static FileStorage getFileStorage(){
        String filestorageType = SystemProperties.getProperties().getProperty("filestorage.type");
        String filestorageHome = SystemProperties.getProperties().getProperty("filestorage.home");
        FileStorage fileStorage = FileStorageFactory.getInstance(filestorageType,filestorageHome).getFileStorage();
        return fileStorage;
    }

    /**
     * 上传文件到文件服务器
     * @param srcPathFileName 本地文件路径名
     * @param destFileName 文件服务器存储文件名
     * @return
     * @throws Exception
     */
    public static String uploadFile(String srcPathFileName, String destFileName) throws Exception{
        try {
            Assert.notEmpty(srcPathFileName,"源文件不能为空");
            Assert.notEmpty(destFileName,"目标文件名不能为空");
            logger.info("上传文件:{} --> {}", srcPathFileName, destFileName);
            FileStorage fileStorage = FileStorageUtils.getFileStorage();
            String fileName = fileStorage.saveFile(srcPathFileName, destFileName);
            logger.info("上传成功 {}", destFileName);
            return fileName;
        }catch (Exception e){
            throw new Exception("上传文件失败:"+srcPathFileName+":"+e.getMessage(),e);
        }
    }

    /**
     * 判断文件在文件服务器中是否存在
     * @param fileName 文件名
     * @return
     */
    public static boolean exists(String fileName){
        FileStorage fileStorage = FileStorageUtils.getFileStorage();
        boolean exists = fileStorage.exists(fileName);
        return exists;
    }

    /**
     * 删除文件
     * @param fileName 文件名
     * @return
     */
    public static boolean delete(String fileName){
        FileStorage fileStorage = FileStorageUtils.getFileStorage();
        return fileStorage.delete(fileName);
    }


    /**
     * 缩放到指定大小
     * @param fileName 原文件名
     * @param toFileName 目标文件名
     * @param width 目标宽
     * @param height 目标高
     * @return
     */
    public static String scaleTo(String fileName,String toFileName,int width,int height){
        FileStorage fileStorage = FileStorageUtils.getFileStorage();
        return fileStorage.scaleTo(fileName,toFileName,width,height);
    }


    /**
     * 根据不同的缩放情况处理缩放
     * @param fileInfoDto
     * @return
     */
    public static String scaleTo(FileInfoDto fileInfoDto){
        String oriFileName = fileInfoDto.getOriFileName();
        String toFileName  = fileInfoDto.getFileName();
        int oldWidth = fileInfoDto.getOriWidth();
        int oldHeight = fileInfoDto.getOriHeight();
        int newWidth  = fileInfoDto.getScaleWidth();
        int newHeight = fileInfoDto.getScaleHeight();
        String ext = FilenameUtils.getExtension(oriFileName);
        FileStorage fileStorage = FileStorageUtils.getFileStorage();
        logger.info("图片缩放处理:{}",fileInfoDto);
        if(FileInfoDto.SCALE_BY_HEIGHT == fileInfoDto.getScaleType()){
//        HEIGHT   表示目标图片只进行高度限制,如:_HEIGHT_200x300;表示裁减后的规格300的高度,长度在保证原图不变形情况下可能会大于200,也可能小于200
//        原文件名: 6ABE5D72FAE4_640x320.jpg
//        输出文件名:6ABE5D72FAE4_640x320_HEIGHT_200x300.jpg
            //高度的缩放比
            float scaleRate =  Float.valueOf(newHeight) /Float.valueOf(oldHeight);
            logger.info("按高度进行缩放:{}",scaleRate);
            //高度不变时,需要对宽度进行的缩放计算得到新的宽度
            int scaleWith = (int)(oldWidth * scaleRate);
            //按高缩放后的名称,与原要求名称不一致
            String scaleFileName = FilenameUtils.getBaseName(oriFileName)+"_HEIGHT_"+scaleWith+"x"+newHeight+"."+FilenameUtils.getExtension(oriFileName);
            if(!FileStorageUtils.exists(scaleFileName)){
                logger.info("文件不存在,开始缩放:{}",scaleFileName);
                //判断如果文件不存在,则进行处理
                FileStorageUtils.scaleTo(oriFileName, scaleFileName, scaleWith, newHeight);
            }else{
                logger.info("文件已存在,跳过缩放:{}",scaleFileName);
            }
            logger.info("按高度进行缩放成功:{}",scaleFileName);
            return scaleFileName;
        }else if(FileInfoDto.SCALE_BY_WIDTH == fileInfoDto.getScaleType()){
//        WIDTH    表示目标图片只进行宽限制,如:_WIDTH_200x300;表示裁减后的规格200的宽度,高度在保证原图不变形情况下可能会大于300,也可能小于300
//        原文件名: 6ABE5D72FAE4_640x320.jpg
//        输出文件名:6ABE5D72FAE4_640x320_WIDTH_200x300.jpg
            //宽度的缩放比
            float scaleRate =  Float.valueOf(newWidth) /Float.valueOf(oldWidth);
            logger.info("按宽度进行缩放:{}",scaleRate);
            //宽度不变时,需要对高度进行的缩放计算得到新的高度
            int scaleHeight = (int)(oldHeight * scaleRate);
            //按宽缩放后的名称,与原要求名称不一致
            String scaleFileName = FilenameUtils.getBaseName(oriFileName)+"_WIDTH_"+newWidth+"x"+scaleHeight+"."+FilenameUtils.getExtension(oriFileName);
            if(!FileStorageUtils.exists(scaleFileName)){
                logger.info("文件不存在,开始缩放:{}",scaleFileName);
                //判断如果文件不存在,则进行处理
                FileStorageUtils.scaleTo(oriFileName, scaleFileName, newWidth, scaleHeight);
            }else{
                logger.info("文件已存在,跳过缩放:{}",scaleFileName);
            }
            logger.info("按宽度进行缩放成功:{}",scaleFileName);
            return scaleFileName;
        }else if(FileInfoDto.SCALE_BY_SIZE == fileInfoDto.getScaleType()){
            //返回的图片的宽和高要求与参数一致。
            //若图片宽和高大于要求值时,先缩小,再进裁剪
            //若图片宽或高小于要求值时,先放大,再进裁剪
            String targetFileName = null;
            //要求的文件名去掉缩放值(80x100)后的前缀,如:11505E06-F876-48E0-93F7-95D218505DAE_288x220_TRUE
            String baseFileNamePrefix = toFileName.substring(0,toFileName.lastIndexOf("_"));
            //用于裁剪时以作中心裁剪
            int afterScaleWidth = 0;
            int afterScaleHeight = 0;
            if(oldWidth >= newWidth && oldHeight >= newHeight){
                //缩小
                float scaleWidthRate =  Float.valueOf(newWidth) /Float.valueOf(oldWidth);
                float scaleHeightRate =  Float.valueOf(newHeight) /Float.valueOf(oldHeight);
                if(scaleWidthRate > scaleHeightRate){
                    //新旧比,宽比值大,表示较接近,刚以此边作为基准进行缩小
                    //宽度不变时,需要对高度进行的缩小计算得到新的高度
                    int scaleHeight = (int)(oldHeight * scaleWidthRate);
                    logger.info("按宽度进行缩小:{}",scaleWidthRate);
                    //按宽缩放后的名称,与原要求名称不一致
                    targetFileName = baseFileNamePrefix+"_"+newWidth+"x"+scaleHeight+"."+ext;
                    afterScaleWidth = newWidth;
                    afterScaleHeight = scaleHeight;
                    if(!FileStorageUtils.exists(targetFileName)){
                        logger.info("文件不存在,开始缩小:{}",targetFileName);
                        //判断如果文件不存在,则进行处理
                        FileStorageUtils.scaleTo(oriFileName, targetFileName, newWidth, scaleHeight);
                    }else{
                        logger.info("文件已存在,跳过缩小:{}",targetFileName);
                    }

                }else{
                    //按高缩小
                    int scaleWith = (int)(oldWidth * scaleHeightRate);
                    logger.info("按高度进行缩小:{}",scaleHeightRate);
                    //按高缩放后的名称,与原要求名称不一致
                    targetFileName = baseFileNamePrefix+"_"+scaleWith+"x"+newHeight+"."+ext;
                    afterScaleWidth = scaleWith;
                    afterScaleHeight = newHeight;
                    if(!FileStorageUtils.exists(targetFileName)){
                        logger.info("文件不存在,开始缩小:{}",targetFileName);
                        //判断如果文件不存在,则进行处理
                        FileStorageUtils.scaleTo(oriFileName, targetFileName, scaleWith, newHeight);
                    }else{
                        logger.info("文件已存在,跳过缩小:{}",targetFileName);
                    }
                }
            }else{
                //放大
                float scaleWidthRate =  Float.valueOf(newWidth) /Float.valueOf(oldWidth);
                float scaleHeightRate =  Float.valueOf(newHeight) /Float.valueOf(oldHeight);
                if(scaleWidthRate > scaleHeightRate){
                    //按宽放大
                    //宽度不变时,需要对高度进行的缩放计算得到新的高度
                    int scaleHeight = (int)(oldHeight * scaleWidthRate);
                    logger.info("按宽度进行放大:{}",scaleWidthRate);
                    //按宽缩放后的名称,与原要求名称不一致
                    targetFileName = baseFileNamePrefix+"_"+newWidth+"x"+scaleHeight+"."+ext;
                    afterScaleWidth = newWidth;
                    afterScaleHeight = scaleHeight;
                    if(!FileStorageUtils.exists(targetFileName)){
                        logger.info("文件不存在,开始放大:{}",targetFileName);
                        //判断如果文件不存在,则进行处理
                        FileStorageUtils.scaleTo(oriFileName, targetFileName, newWidth, scaleHeight);
                    }else{
                        logger.info("文件已存在,跳过放大:{}",targetFileName);
                    }

                }else{
                    //按高放大
                    int scaleWith = (int)(oldWidth * scaleHeightRate);
                    logger.info("按高度进行放大:{}",scaleHeightRate);
                    //按高缩放后的名称,与原要求名称不一致
                    targetFileName = baseFileNamePrefix+"_"+scaleWith+"x"+newHeight+"."+ext;
                    afterScaleWidth = scaleWith;
                    afterScaleHeight = newHeight;
                    if(!FileStorageUtils.exists(targetFileName)){
                        logger.info("文件不存在,开始放大:{}",targetFileName);
                        //判断如果文件不存在,则进行处理
                        FileStorageUtils.scaleTo(oriFileName, targetFileName, scaleWith, newHeight);
                    }else{
                        logger.info("文件已存在,跳过放大:{}",targetFileName);
                    }
                }
            }
            //对目标文件进行裁剪scaleFileName
            logger.info("裁剪:{} --> {}",targetFileName,toFileName);
            //中心裁剪
            int x = (afterScaleWidth - newWidth) / 2;
            int y = (afterScaleHeight - newHeight) / 2 ;
            if(x <  0 || y < 0){
                //计算异常时,不处理中心裁剪
                x = 0;
                y = 0;
            }
            fileStorage.cutImg(targetFileName,toFileName,newWidth,newHeight,x,y);
            logger.info("裁剪成功:{}",toFileName);
            return toFileName;
        }else if(FileInfoDto.SCALE_BY_CENTER == fileInfoDto.getScaleType()){
            //返回的图片的宽和高要求与参数一致。直接缩放到指定的大小
            logger.info("直接缩放到指定的大小:{}", toFileName);
            if(!FileStorageUtils.exists(toFileName)){
                logger.info("文件不存在,开始缩放:{}",toFileName);
                FileStorageUtils.scaleTo(oriFileName, toFileName, newWidth, newHeight);
            }else{
                logger.info("文件已存在,跳过缩放:{}",toFileName);
            }
            logger.info("缩放成功:{}",toFileName);
            return toFileName;
        }else{
            throw new RuntimeException("not support scale type:"+fileInfoDto.getScaleType());
        }
    }

    /**
     * 上传文件到MongoDb或文件服务器
     * @param srcPathFileName
     * @param destFileName
     * @param deleteBeforeUpload 上传之前是否先执行删除,MongoDb是上传默认图时使用
     * @return
     * @throws Exception
     */
    public static String uploadFileWithMongoDbOrFileServer(String srcPathFileName, String destFileName,boolean deleteBeforeUpload) throws Exception{
        try {
            Assert.notEmpty(srcPathFileName,"源文件不能为空");
            Assert.notEmpty(destFileName,"目标文件名不能为空");
            String fileName = null;
            String fileStorageOpen =  SystemProperties.getProperties().getProperty("filestorage.open");
            if (StringUtils.COMMON_VALUE_1.equals(fileStorageOpen)) {
                //使用文件服务器进行存储
                //保存到文件服务器 --2016-04-25 by wkq
                fileName = FileStorageUtils.uploadFile(srcPathFileName, destFileName);
            }else if (StringUtils.COMMON_VALUE_2.equals(fileStorageOpen)) {
                //使用阿里OSS存储
                AliOssClient.getInstance().upload(srcPathFileName,destFileName);
                fileName = destFileName;
            } else {
                //使用原来的MongoDb存储
                logger.info("上传文件MongoDb:{} --> {}", srcPathFileName, destFileName);

                GridFS gridFS = new GridFS(MongoDb.getInstance().getDb());
                if(deleteBeforeUpload) {
                    try {
                        GridFSDBFile f = gridFS.findOne(destFileName);
                        if (f != null) {
                            gridFS.remove(destFileName);
                        }
                    } catch (IllegalArgumentException ex) {
                        logger.error("delete from MongoDb,file not found");
                    }
                }
                File oriFile = new File(srcPathFileName);
                GridFSInputFile gfsFile = gridFS.createFile(oriFile);
                gfsFile.setFilename(destFileName);
                gfsFile.save();
                fileName = destFileName;
                logger.info("上传成功MongoDb {}", destFileName);
            }
            return fileName;
        }catch (Exception e){
            throw new Exception("上传文件失败:"+srcPathFileName+":"+e.getMessage(),e);
        }
    }


    /**
     * 根据文件名解析得到文件信息
     * @param fileName 包含文件缩放信息的文件名
     * @return
     */
    public static FileInfoDto getFileInfo(String fileName){
        try {
            //得到原文件名
            FileInfoDto fileInfoDto = new FileInfoDto();
            fileInfoDto.setFileName(fileName);

            //解析得到原文件名
            String oriFileName = null;//原文件名
            String prefixName = "";//原文件名前缀名
            int first_ = fileName.indexOf("_");
            int index_TRUE_ = fileName.indexOf("_TRUE_");
            int index_HEIGHT_ = fileName.indexOf("_HEIGHT_");
            int index_CENTER_ = fileName.indexOf("_CENTER_");
            int index_WIDTH_ = fileName.indexOf("_WIDTH_");
            int index_XING = fileName.indexOf("*");

            String ext = FilenameUtils.getExtension(fileName);//png
            if (index_XING != -1 && first_ != -1) {// 11505E06-F876-48E0-93F7-95D218505DAE*288x220_TRUE_88x54.png
                prefixName = fileName.substring(0, first_);//11505E06-F876-48E0-93F7-95D218505DAE*288x220
            } else if (index_TRUE_ != -1 || index_HEIGHT_ != -1 || index_WIDTH_ != -1 || index_CENTER_ != -1) {
                // 11505E06-F876-48E0-93F7-95D218505DAE_288x220_TRUE_88x54.png
                if (index_TRUE_ != -1) {
                    prefixName = fileName.substring(0, index_TRUE_);
                } else if (index_HEIGHT_ != -1) {
                    prefixName = fileName.substring(0, index_HEIGHT_);
                } else if (index_CENTER_ != -1) {
                    prefixName = fileName.substring(0, index_CENTER_);
                } else if (index_WIDTH_ != -1) {
                    prefixName = fileName.substring(0, index_WIDTH_);
                }
            } else if (first_ != -1) {
                //原文件 11505E06-F876-48E0-93F7-95D218505DAE_288x220.png
                //或有缩放 11505E06-F876-48E0-93F7-95D218505DAE_288x220_400x600.png
                String subFileName = fileName.substring(first_ + 1, fileName.length());
                if (subFileName.indexOf("_") != -1) {
                    //有缩放 11505E06-F876-48E0-93F7-95D218505DAE_288x220_400x600.png
                    prefixName = fileName.substring(0, fileName.lastIndexOf("_"));
                    fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_SIZE);
                } else {
                    //无缩放
                    prefixName = FilenameUtils.getBaseName(fileName);
                    fileInfoDto.setScaleType(FileInfoDto.NO_SCALE);
                }
            } else {
                //原文件名,无缩放,无大小划线
                prefixName = FilenameUtils.getBaseName(fileName);
            }
            oriFileName = prefixName + "." + ext;//11505E06-F876-48E0-93F7-95D218505DAE*288x220.png
            fileInfoDto.setOriFileName(oriFileName);
            fileInfoDto.setExt(ext);
            //处理缩放
            fileInfoDto.setScaleType(FileInfoDto.NO_SCALE);//默认无缩放
            String oriSizeStr = "";
            if (index_XING != -1) {
                oriSizeStr = fileName.substring(index_XING + 1, first_);
            } else {
                String subFileName = fileName.substring(first_ + 1, fileName.length());
                if (subFileName.indexOf("_") != -1) {
                    oriSizeStr = subFileName.substring(0, subFileName.indexOf("_"));
                }
            }
            String[] oldSizes = oriSizeStr.split("x");
            if (oldSizes != null && oldSizes.length > 1 && isNum(oldSizes[0], oldSizes[1])) {
                int oriWidth = Integer.parseInt(oldSizes[0]);   //原图宽
                int oriHeight = Integer.parseInt(oldSizes[1]);  //原图高
                fileInfoDto.setOriWidth(oriWidth);
                fileInfoDto.setOriHeight(oriHeight);
                //缩放的尺寸
                String newSizeStr = fileName.substring(fileName.lastIndexOf("_") + 1, fileName.lastIndexOf("."));//缩放要求的尺寸
                String[] newSizes = newSizeStr.split("x");
                if (newSizes != null && newSizes.length > 1 && isNum(newSizes[0], newSizes[1])) {
                    int newWidth = Integer.parseInt(newSizes[0]);
                    int newHeight = Integer.parseInt(newSizes[1]);
                    fileInfoDto.setScaleWidth(newWidth);
                    fileInfoDto.setScaleHeight(newHeight);
                    //只有正确得到尺寸才是缩放
                    if (index_TRUE_ != -1) {
                        fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_SIZE);
                    } else if (index_HEIGHT_ != -1) {
                        fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_HEIGHT);
                    } else if (index_CENTER_ != -1) {
                        fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_CENTER);
                    } else if (index_WIDTH_ != -1) {
                        fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_WIDTH);
                    } else {
                        fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_SIZE);
                    }
                }
            }
            return fileInfoDto;
        }catch (Exception e){
            throw new ZdnstException(BaseCode.ERROR_CODE112,"请求文件名解析异常:"+e.getMessage(),e);
        }
    }


    /**
     * 长度是否都是数字格式
     * @param w
     * @param h
     * @return
     */
    private static boolean isNum(String w,String h){
        Pattern pattern = Pattern.compile("[0-9]*");
        boolean isNum = pattern.matcher(w).matches()&&pattern.matcher(h).matches();  //都是数字
        return isNum;
    }

}
package com.zdnst.common.infra.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
 * 系统配置文件
 */
public class ConfigUtils {

    private static Logger logger = LoggerFactory.getLogger(ConfigUtils.class);

    // 应用根目录
    private String rootPath = null;
    // classes目录
    private String classPath = null;

    private static ConfigUtils instance = new ConfigUtils();

    private ConfigUtils() {

        logger.info("OS NAME:{}", System.getProperty("os.name"));

        URL url = this.getClass().getClassLoader().getResource("/");

        if (url == null) {

            url = ConfigUtils.class.getResource("/");

        }

        classPath = url.getFile();

        if (System.getProperty("os.name") != null
                && System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1
                && classPath.startsWith("/")) {

            classPath = classPath.substring(1);

        }

        classPath = classPath.replace("%20", " ");

        rootPath = classPath.replace("/WEB-INF/classes/", "");

        rootPath = rootPath.replace("%20", " ");

        logger.info("classPath:" + classPath);

        logger.info("rootPath:" + rootPath);

    }

    /**
     * 取唯一的cfg实例
     *
     * @return 唯一的cfg实例
     */
    public static synchronized ConfigUtils getInstance() {
        return instance;
    }

    /**
     * 工具方法,读取Properties配置文件
     *
     * @param propPath properties配置文件绝对路径
     * @return Properties
     */
    public static Properties loadProperties(String propPath) {
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(propPath));
            properties.load(inputStream);
        } catch (IOException e) {
            logger.error("load properties error." + propPath, e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    logger.warn("load properties error:" + e.getMessage());
                }
            }
        }
        return properties;
    }

    /**
     * 获取应用根目录(网站根目录,如d:\MyApp)
     *
     * @return
     */
    public String getRoot() {
        return rootPath;
    }


    /**
     * 取WEB-INF绝对路径
     *
     * @return WEB-INF绝对路径目录(eg:/X:/XXX//WEB-INF/)
     */
    public String getWebInf() {
        if (classPath.indexOf("WEB-INF") != -1) {
            return getRoot() + "/WEB-INF/";
        } else {
            logger.warn("no WEB-INF path in current environment. return the root path instead.");
            return getRoot();
        }
    }

    /**
     * 取类的运行根目录的绝对路径
     *
     * @return classes绝对路径目录(eg:在web环境中返回/X:/XXX//WEB-INF/classes/)
     */
    public String getClassPath() {
        return classPath;
    }


    public static void main(String[] args) {
        System.out.println(ConfigUtils.getInstance().getRoot());
        System.out.println(ConfigUtils.getInstance().getWebInf());
    }

}

转载于:https://my.oschina.net/u/2322635/blog/1627839

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值