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

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

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

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

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

   

<repositories>
   <repository>
       <id>AsposeJavaAPI</id>
       <name>Aspose Java API</name>
       <url>http://repository.aspose.com/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   2020/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   2020/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 转为pdf
        String 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   2020/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;
                }
                //得到各个run
                RunCollection 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);
                    }
                }
            }
            //去除空白的table
            for (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转换pdf
                        PdfUtil.excel2pdfNew(fileInputStream,response.getOutputStream());
                        prefix=".pdf";
                    }else if(type.equalsIgnoreCase("docx") || type.equalsIgnoreCase("doc")){
                        //word文档
						//调用工具类将word转换pdf
                        PdfUtil.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());
            }

    }

官网参考地址:

https://blog.aspose.com/2014/08/12/aspose-for-maven-aspose-cloud-maven-repository/

官网github示例项目地址:

https://github.com/aspose-words/Aspose.Words-for-Java

 

 

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
首先机子上安装有office,在COM中添加引用Microsoft.Word.11.0.Object.Library(或11.0以上) Microsoft.Office.Interop.Word.Application myWordApp = null; Microsoft.Office.Interop.Word.Document doc = null; object Filename = path + "\\" + TaskID + ".docx";//目的文件 object templateFile = System.Windows.Forms.Application.StartupPath + @"\Template.docx";//模板文件,有一个五列一行的表 System.IO.File.Copy(templateFile.ToString(), Filename.ToString(), true);//模板WORD中有一个五列的表头,分别是卡号,串口号,发送指令条数,接收指令条数,收发成功率 myWordApp = new Microsoft.Office.Interop.Word.Application(); doc = myWordApp.Documents.Open(ref Filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); /////显示页码 object oAlignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter; object oFirstPage = true; oAlignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter; myWordApp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add(ref oAlignment, ref oFirstPage); myWordApp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.NumberStyle = Microsoft.Office.Interop.Word.WdPageNumberStyle.wdPageNumberStyleNumberInDash; for (int i = 2; i < 102; i++)//举例100台 { doc.Tables[1].Rows.Add(ref Nothing);//表格增加一行 doc.Tables[1].Cell(i, 1).Range.Text = "250297";//卡号 doc.Tables[1].Cell(i, 2).Range.Text = "COM12";//串口号 doc.Tables[1].Cell(i, 3).Range.Text = "100";//发送指令条数 doc.Tables[1].Cell(i, 4).Range.Text = "99";//接收指令条数 doc.Tables[1].Cell(i, 5).Range.Text = "99%";//收发成功率 } doc.SaveAs(ref Filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); object savechanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;//不保存挂起的更改 ////下面是直接打印,文档不显示 //doc.PrintOut(ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); object readOnly=false; object isVisable = true;////文档打开状态为可视 doc = myWordApp.Documents.Open(ref Filename, ref Nothing, ref readOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref isVisable, ref Nothing, ref Nothing, ref Nothing, ref Nothing); doc.PrintPreview();//打印预览
对于Aspose.Words,可以使用它将Word文档转换为PDF格式,然后使用PDF.js进行在线预览Aspose.Words是一个功能强大的文档处理库,可以帮助开发人员处理和转换多种文档格式。通过使用Aspose.WordsWord文档转换为PDF,可以确保预览的准确性和稳定性。 转换步骤如下: 1. 使用Aspose.Words将服务器存储的Word文档转换为PDF格式。 2. 使用PDF.js来加载和显示转换后的PDF文件,从而实现在线预览。 这种方法相对于使用ce.office.extension将Word文件转换为HTML预览,能够避免一些格式、图片和字体错乱的问题,因为PDF是一种更稳定和可靠的文档格式。 需要注意的是,使用Aspose.Words进行WordPDF时,可能会遇到试用版自动加水印的问题。如果需要去除水印,可以参考相应的教程进行操作。但是请注意,我们在这里只提供思路和参考,具体操作还需要根据你的实际需求和情况进行调整。 总结起来,aspose.words可以通过将Word转换为PDF格式,然后使用PDF.js进行在线预览。这种方法可以提供更准确和稳定的预览效果。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Net Core3.1使用Aspose.Words18.4将WordPDF](https://blog.csdn.net/xiaomai4343/article/details/125384428)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [【2020.12】Aspose.words 20.12最新版Crack,wordpdf去水印方法](https://blog.csdn.net/xiaostuart/article/details/111479549)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

成伟平2022

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值