Bootstrap

PDF预览,下载

PDF预览,下载

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.*;

public class PDFUtils {

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

    /**
     * Word 转 PDF
     *
     * @param inPath  word文件地址
     * @param outPath pdf文件地址
     */
    public static void doc2pdf(String inPath, String outPath) {
        File wordFile = new File(inPath);
        if (!wordFile.exists()) {
            logger.info("源文件不存在:{}", inPath);
            return;
        }

        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return;
        }
        try {
            logger.info("PDF转换开始");
            //开始时间
            long old = System.currentTimeMillis();
            //获取文件
            File file = new File(outPath);
            //获取文件流
            FileOutputStream os = new FileOutputStream(file);
            // Address是将要被转化的word文档
            Document doc = new Document(inPath);
            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF
            doc.save(os, SaveFormat.PDF);
            //结束时间
            long now = System.currentTimeMillis();
            logger.info("PDF转换结束 共耗时:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 去除水印
     *
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        String imgPath = "config/Aspose.Words.lic";//文件到Aning中pdf去除水印文件夹中取
        InputStream is = null;
        try {
            is = PDFUtils.class.getClassLoader().getResourceAsStream(imgPath);// Aspose.Words.lic应放在..src 下面
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 用流读出数据   预览
     *
     * @param res
     * @param filePaths
     * @throws Exception
     */
    public void readAndDownload(HttpServletResponse res, String filePaths, String path) throws Exception {


        //截取路径

        filePaths = path + filePaths.substring(filePaths.indexOf("/userfiles/"));
        String fileExtension = filePaths.substring(filePaths.lastIndexOf("."));
        if (".doc".equals(fileExtension) || ".docx".equals(fileExtension)) {
            getDocOutStream(res, filePaths);
        } else if (".pdf".equals(fileExtension)) {
            getPdfOutStream(res, filePaths);
        } else {
            getPhotoOutStream(res, filePaths);
        }
    }

    /**
     * word 文档转换成pdf预览
     *
     * @param res
     * @param filePaths
     * @throws Exception
     */
    private void getDocOutStream(HttpServletResponse res, String filePaths) throws Exception {

        String fileName = filePaths.substring(0, filePaths.lastIndexOf(".")) + ".pdf";
        File file = new File(fileName);
        if (!file.exists()) {
            if (!getLicense()) { // 验证License 若不验证则转化出的文档会有水印产生
                return;
            }
            OutputStream out = null;
            ByteArrayOutputStream os = null;
            try {
                out = res.getOutputStream();
                res.setContentType("application/pdf");
                os = new ByteArrayOutputStream();
                Document doc = new Document(filePaths);// 读取文档
                doc.save(os, SaveFormat.PDF);// 转成pdf
                out.write(os.toByteArray());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //关闭流
                if (out != null) {
                    try {
                        out.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }


        } else {
            getPdfOutStream(res, fileName);
        }

    }

    /**
     * pdf文件直接输出   预览
     *
     * @param res
     * @param filePaths
     * @throws IOException
     */
    private void getPdfOutStream(HttpServletResponse res, String filePaths) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        try {
            out = res.getOutputStream();
            res.setContentType("application/pdf");

            if (filePaths != null) {
                in = new FileInputStream(filePaths);
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = in.read(b)) != -1) {
                    out.write(b, 0, len);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


    }

    private void getPhotoOutStream(HttpServletResponse res, String filePaths) throws Exception {
        Document doc = new Document();
        OutputStream out = res.getOutputStream();
        DocumentBuilder builder = new DocumentBuilder(doc);
        ImageIcon imageIcon = new ImageIcon(filePaths);
        int iconWidth = imageIcon.getIconWidth();
        int iconHeight = imageIcon.getIconHeight();

        if (iconWidth > 210) {
            iconHeight = 210 * iconHeight / iconWidth;
            iconWidth = 210;
        }
        if (iconHeight > 297) {
            iconWidth = 297 * iconWidth / iconHeight;
            iconHeight = 297;
        }
        InputStream in = null;
        ByteArrayOutputStream os = null;
        try {
            in = new FileInputStream(filePaths);
            builder.insertImage(in, iconWidth, iconHeight);
            os = new ByteArrayOutputStream();
            doc.save(os, SaveFormat.PDF);// 转成pdf
            out.write(os.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


    }

    /**
     * 文件下载
     *
     * @param filePath pdf文件路径
     * @param response
     * @param fname    下载文件名称带文件后缀
     * @throws IOException
     */
    public void download(String filePath, HttpServletResponse response, String fname) throws IOException {
        System.out.println("filePath:" + filePath);
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] bs = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要

        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment; filename="
                + new String(fname.getBytes("utf-8"), "ISO-8859-1"));

        OutputStream out = response.getOutputStream();
        while ((len = br.read(bs)) > 0) {
            out.write(bs, 0, len);
        }
        out.flush();
        out.close();
        br.close();
    }

    /**
     * @param filesrc  图片路径
     * @param pathFile 可以为空字符串
     * @throws Exception
     */
    private void changePhotoToPdf(String filesrc, String pathFile) throws Exception {
        InputStream in = null;
        OutputStream out = null;
        ByteArrayOutputStream os = null;
        try {
            Document doc = new Document();
            File outFile = new File(pathFile + filesrc.substring(0, filesrc.indexOf(".")) + ".pdf");
            out = new FileOutputStream(outFile);
            DocumentBuilder builder = new DocumentBuilder(doc);
            ImageIcon imageIcon = new ImageIcon(pathFile + filesrc);
            int iconWidth = imageIcon.getIconWidth();
            int iconHeight = imageIcon.getIconHeight();

            if (iconWidth > 210) {
                iconHeight = 210 * iconHeight / iconWidth;
                iconWidth = 210;
            }
            if (iconHeight > 297) {
                iconWidth = 297 * iconWidth / iconHeight;
                iconHeight = 297;
            }
            in = new FileInputStream(pathFile + filesrc);
            builder.insertImage(in, iconWidth, iconHeight);
            os = new ByteArrayOutputStream();
            doc.save(os, SaveFormat.PDF);// 转成pdf
            out.write(os.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
//转成pdf
	public static void outPdf(String outPathName, Document doc) {
			ByteArrayOutputStream os =null;
			OutputStream	out =null;
				os = new ByteArrayOutputStream();
				try {
					doc.save(os, SaveFormat.PDF);
					File outFile = new File(outPathName);
					out = new FileOutputStream(outFile);
					out.write(os.toByteArray());
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					if (out != null) {
						try {
							out.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					if (os != null) {
						try {
							os.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
		
	}
	

	/**
	 * 下载zip输出
	 * @param tempPath
	 * @param fiName
	 * @param res
	 * @throws IOException
	 */
	public static void outPutStream(String tempPath, String fiName, HttpServletResponse res) throws IOException {
		
		OutputStream out=null;
		InputStream in =null;
		ByteArrayOutputStream os=null;
		try {
		String filePaths=tempPath+fiName+".zip";
		 res.setCharacterEncoding("UTF-8");
		 res.setContentType("application/octet-stream");
		 res.setHeader("Content-disposition",
		         "attachment; filename=" + java.net.URLEncoder.encode(fiName+".zip", "UTF-8"));
		
		 out = res.getOutputStream();
		
		 os = new ByteArrayOutputStream();
		if (filePaths != null) {
			in = new FileInputStream(filePaths);
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = in.read(b)) != -1) {
				out.write(b, 0, len);
			}
		}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			//关闭流
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
;