700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 使用aspose组件将word excel转换成pdf 实现预览

使用aspose组件将word excel转换成pdf 实现预览

时间:2022-06-22 16:03:38

相关推荐

使用aspose组件将word excel转换成pdf  实现预览

第一步 : 引入相关jar包。(两种方式)

方式一: 直接下载jar包上传到私服,或者通过引入本地依赖的方式进行引入jar包 ,jar包下载地址:/repo/com/aspose/

方式二:通过直接映入依赖的方式进行下载,

先引入jar包所在仓库地址:

<repositories><repository><id>AsposeJavaAPI</id><name>Aspose Java API</name><url>/repo/</url></repository></repositories>

然后引入依赖配置

word相关依赖

<dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>20.9</version></dependency>

excel相关依赖

<dependency><groupId>com.aspose</groupId><artifactId>aspose-cells</artifactId><version>20.9</version></dependency>

第二步:编写 word、excel转换成pdf工具类代码:

package utils;import cn.hutool.core.util.StrUtil;import com.aspose.cells.PdfSaveOptions;import com.aspose.cells.SaveFormat;import com.aspose.cells.Style;import com.aspose.cells.Workbook;import com.aspose.words.*;import org.springframework.core.io.ClassPathResource;import javax.servlet.http.HttpServletResponse;import javax.wsdl.Output;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;public class PdfUtil {private static boolean getLicense() {/*boolean result = false;try {String filePath = "/License.xml";ClassPathResource classPathResource = new ClassPathResource(filePath);InputStream is =classPathResource.getInputStream();// InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream(""); // license.xml应放在..\WebRoot\WEB-INF\classes路径下License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}*/boolean result = true;return result;}/*** @param wordPath 需要被转换的word全路径带文件名* @param pdfPath 转换之后pdf的全路径带文件名*/public static void doc2pdf(String wordPath, String pdfPath) {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return;}try {long old = System.currentTimeMillis();File file = new File(pdfPath); //新建一个pdf文档FileOutputStream os = new FileOutputStream(file);Document doc = new Document(wordPath); //Address是将要被转化的word文档doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换long now = System.currentTimeMillis();os.close();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时} catch (Exception e) {e.printStackTrace();}}/*** @param excelPath 需要被转换的excel全路径带文件名* @param pdfPath 转换之后pdf的全路径带文件名*/public static void excel2pdf(String excelPath, String pdfPath) {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return;}try {long old = System.currentTimeMillis();Workbook wb = new Workbook(excelPath);// 原始excel路径FileOutputStream fileOS = new FileOutputStream(new File(pdfPath));wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);fileOS.close();long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时} catch (Exception e) {e.printStackTrace();}}/*** @Description* @Author chengweiping* @Date /11/13 10:50*/public static void excel2pdfNew(InputStream inputStream, OutputStream outputStream) {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return ;}try {/* FontSettings.setFontsFolder(File.separator + "usr"+ File.separator + "share" + File.separator + "fonts", true);*/long old = System.currentTimeMillis();Workbook wb = new Workbook(inputStream);// 原始excel路径PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();//缩放到一个页面(如果列太多 太长)pdfSaveOptions.setOnePagePerSheet(true);//重点,设置所有列放在一页里,会自动适应宽度pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);wb.save(outputStream,pdfSaveOptions);long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时} catch (Exception e) {e.printStackTrace();}}/*** @Description* @Author chengweiping* @Date /11/13 10:53*/public static void doc2pdfNew(InputStream inputStream, OutputStream outputStream) {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return;}try {long old = System.currentTimeMillis();Document doc = new Document(inputStream); //Address是将要被转化的word文档try{//去掉无用的空白行,解决空白页问题removeBlank(doc);}catch (Exception e){e.printStackTrace();}com.aspose.words.PdfSaveOptions pdfSaveOptions=new com.aspose.words.PdfSaveOptions();pdfSaveOptions.setExportDocumentStructure(true);doc.save(outputStream,pdfSaveOptions);// doc.save(outputStream, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {//word 和excel 转为pdfString filePaths="D:/tip.docx";String fileName="2";String pdfPath="D:/pic/"+fileName+".pdf";doc2pdf(filePaths, pdfPath);//filePaths需要转换的文件位置 pdfPath为存储位置// String excel2pdf="D:/2.xlsx";}/*** @Description 移除空白行* @Author chengweiping* @Date /11/24 14:31*/public static void removeBlank(Document document) {for (Section section : document.getSections()) {//删除空白页部分if (StrUtil.isBlank(section.getBody().getText())){document.removeChild(section);}//得到所有段落for (Paragraph paragraph : section.getBody().getParagraphs()) {//flag代表该段落有没有图片boolean flag = false;if (paragraph.getChildNodes(NodeType.SHAPE,true).getCount()==0){flag = true;}//得到各个runRunCollection runs = paragraph.getRuns();if (flag){//首先去除各个部分的转义字符,如果删除之后run为空则去除for (Run run : runs) {try {run.setText(run.getText().replaceAll("[\f|\r|\n]",""));} catch (Exception e) {e.printStackTrace();}}//删除空白的paragraph,如果有图片则不删除,String content = StrUtil.cleanBlank(paragraph.getText());if (StrUtil.isBlank(content)){section.getBody().getParagraphs().remove(paragraph);}}}//去除空白的tablefor (Table table : section.getBody().getTables()) {for (Row row : table.getRows()) {for (Cell cell : row.getCells()) {if (StrUtil.isBlank(cell.getText())){row.getCells().remove(cell);}}if (StrUtil.isBlank(row.getText())){table.getRows().remove(row);}}if (StrUtil.isBlank(table.getText())){section.getBody().getTables().remove(table);}}}}}

controller层,在线预览示例代码(对excel、word进行转换成pdf)

@ApiOperation("在线预览")@RequestMapping(value = "/preview", method = RequestMethod.GET)public void preview(HttpServletRequest request,HttpServletResponse response) throws Exception {String prefix=".pdf";String fileName="demo";String userAgent = request.getHeader("User-Agent");BufferedInputStream fileInputStream =null;try {response.setContentType("application/pdf");//#getFileInputStream()方法根据自己需求实际情况,或许需要转换的word或excel文件输入流fileInputStream= getFileInputStream()// 获取文件后缀String type=fileUploadName.substring(fileUploadName.lastIndexOf(".")).replace(".","").trim();if(type.equalsIgnoreCase("xlsx") || type.equalsIgnoreCase("xls") ){//excel文档//调用工具类将excel转换pdfPdfUtil.excel2pdfNew(fileInputStream,response.getOutputStream());prefix=".pdf";}else if(type.equalsIgnoreCase("docx") || type.equalsIgnoreCase("doc")){//word文档//调用工具类将word转换pdfPdfUtil.doc2pdfNew(fileInputStream,response.getOutputStream());prefix=".pdf";}request.setCharacterEncoding("UTF-8");response.setHeader("Content-Disposition", "inline; filename=" + fileName+prefix);response.setHeader("filename",fileName);} catch (Exception e) {e.printStackTrace();}finally {IoUtil.close(fileInputStream);IoUtil.close(response.getOutputStream());}}

官网参考地址:

//08/12/aspose-for-maven-aspose-cloud-maven-repository/

官网github示例项目地址:

/aspose-words/Aspose.Words-for-Java

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。