ASPOSE合併多個pdf並轉換多種類型的文件(word、excel、email、img)成PDF文件

 

1.在本地電腦上引入附件轉換需要的依賴庫。

有兩種方式添加依賴:

1)配置aspose遠程倉庫地址

   在settings.xml文件中添加配置:

 

     <profile>

      <id>jdk-1.6</id>

 

      <activation>

        <jdk>1.6</jdk>

      </activation>

 

      <repositories>

        <repository>

        <id>AsposeJavaAPI</id>

        <name>Aspose Java API</name>

        <url>http://repository.aspose.com/repo/</url>

        </repository>

      </repositories>

</profile>



然後從官網查看aspose.email,aspose.words.aspose.excel,aspose.pdf等依賴,添加到pom文件中,即可。如:

<dependency>

<groupId>com.aspose</groupId>

<artifactId>aspose-email</artifactId>

<version>20.3</version>

<classifier>jdk16</classifier>

</dependency>



2) 在私庫中下載jar包,然後把下好的jar包放到本地倉庫,然後在idea裏本地導入到項目中。

私庫地址:

https://repository.aspose.com/repo/com/aspose/

導入步驟

File-> Project Structure ->Modules







 

2.調試附件轉換的功能,實現圖片轉PDF,word轉換爲PDF,PDF合成PDF功能。

下面是2個圖片放到一個pdf整合的效果,實現步驟大同小異,因此直接先看效果圖:



需要注意的是: 使用postman測試兩個word合併時,需要在Headers裏面設置Content-Type=multipart/form-data,否則接受不到2個文件。另外form-data裏面需要設置參數的key爲文件才能選擇文件進行作爲參數傳給接口。







圖片轉爲pdf功能:

 

1)添加依賴:

 <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-imaging</artifactId>
            <version>20.3</version>
            <classifier>jdk16</classifier>
</dependency>

 注: 需要在setting文件裏設置aspose的倉庫。

工具類如下:

package com.example.cn.service;

import com.aspose.imaging.Image;
import com.aspose.imaging.License;
import com.aspose.imaging.imageoptions.PdfOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
@Slf4j
public class ImgService {

    @Autowired
    private LicenseService licenseService;

  
    private void getLicense() {
        License license = new License();
        try {
            license.setLicense(licenseService.getLicense());
        } catch (Exception e) {
            log.error("鑑權發生錯誤: [{}]", e);
        }
    }

 
    public void imgToPdf(InputStream file, String path) {
        getLicense();
        Image image = Image.load(file);
        image.save(path, new PdfOptions());

    }

    

}

controller:

   @GetMapping(value = "/toPdfAndMerge")
    public ResponseEntity<String> fileUpload(@RequestParam(name = "file1", required = false)
                                                     MultipartFile file1,
                                             @RequestParam(name = "file2", required = false)
                                                     MultipartFile file2) throws Exception {

        List<FileCO> fileCOs = new ArrayList<>();
        if (file1 != null) {
            FileCO fileCO = new FileCO();
            fileCO.setFileContent(file1.getBytes());
            fileCO.setFileName(file1.getOriginalFilename());
            fileCOs.add(fileCO);
        }
        if (file2 != null) {
            FileCO fileCO2 = new FileCO();
            fileCO2.setFileContent(file2.getBytes());
            fileCO2.setFileName(file2.getOriginalFilename());
            fileCOs.add(fileCO2);
        }
        return ResponseEntity.ok(pdfMergeService.testService(fileCOs));
    }

service:

   public String transformation(FileCO fileCO, String type) throws Exception {
        String pdf = "pdf";
        String txt = "txt";
        List<String> xls = Arrays.asList("xls", "xlt", "xml");
        List<String> doc = Arrays.asList("doc", "rtf", "dot");
        List<String> ppt = Arrays.asList("pps", "pot", "ppt");
        List<String> img = Arrays.asList("jpg", "png", "tif", "bmp");
        List<String> eml = Arrays.asList("msg", "eml", "mht", "pst", "ost");
        InputStream file = new ByteArrayInputStream(fileCO.getFileContent());
        String fileName = fileCO.getFileName();
        //取後綴名
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //只取三位
        suffix = suffix.substring(0, 3).toLowerCase();
        String uuid = UUID.randomUUID().toString();

        String lastPath = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDate.now()) + "/";
        File dateFile = new File(path + lastPath);
        if (!dateFile.exists()) {
            //創建日期目錄
            dateFile.mkdirs();
        }
        //圖片只做壓縮
        if (img.contains(suffix)) {
            lastPath = lastPath + uuid + ".jpg";
        } else if (xls.contains(suffix)) {
            lastPath = lastPath + uuid + ".html";
        } else {
            if (CommonCodeUtils.TO_PDF.equals(type)) {
             lastPath = lastPath + uuid + ".pdf";
            }
            if (CommonCodeUtils.TO_HTML.equals(type)) {
                lastPath = lastPath + uuid + ".html";
            }
        }


        String fullPath = path + lastPath;

        if (pdf.equals(suffix)) {
            if (CommonCodeUtils.TO_HTML.equals(type)) {
                pdfService.pdfToHtml(file, fullPath);
            }
            if (CommonCodeUtils.TO_PDF.equals(type)) {
                pdfService.pdfToPdf(file, fullPath);
            }
        } else if (xls.contains(suffix)) {
            //excel只壓縮爲html
            // if (CommonCodeUtils.TO_HTML.equals(type)) {
            excelService.excelToHtml(file, fullPath);
            // }
            // if (CommonCodeUtils.TO_PDF.equals(type)) {
            //    excelService.excelToPdf(file, fullPath);
            // }
        } else if (doc.contains(suffix)) {
            if (CommonCodeUtils.TO_HTML.equals(type)) {
                wordService.wordToHtml(file, fullPath);
            }
            if (CommonCodeUtils.TO_PDF.equals(type)) {
                wordService.wordToPdf(file, fullPath);
            }
        } else if (ppt.contains(suffix)) {
            if (CommonCodeUtils.TO_HTML.equals(type)) {
                pptService.pptToHtml(file, fullPath);
            }
            if (CommonCodeUtils.TO_PDF.equals(type)) {
                pptService.pptToPdf(file, fullPath);
            }
        } else if (img.contains(suffix)) {
            //現在圖片走壓縮,統一轉爲jpg
           // imgService.imgToPdf(file,fullPath);
           // ImageHelper.scaleImage(file, fullPath, imageScale, "jpg");
            if (CommonCodeUtils.TO_PDF.equals(type)){
                imgService.imgToPdf(file,fullPath);
            }

        } else if (eml.contains(suffix)) {

//            byte[] bytes=fileCO.getFileContent();
//            getFileByBytes(bytes,fullPath);
            if (CommonCodeUtils.TO_PDF.equals(type)) {
             // mailService.emlToHtml(file, fullPath);
                mailService.emlToPdf(file,fullPath);
            }
        } else if (txt.contains(suffix)) {
            txtService.txtToHtml(fileCO.getFileContent(), fullPath, fileName);
        } else {
            return null;
        }

        return lastPath;
    }

合併pdf文件:

 public void mergePdfFiles(List<String> files, String newFile) throws IOException, DocumentException {
        PdfReader pdfReader = new PdfReader(files.get(0));
        Document document = new Document(pdfReader.getPageSize(1));
        pdfReader.close();
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(newFile));
        document.open();
        for (int i = 0; i < files.size(); i++) {
            PdfReader reader = new PdfReader(files.get(i));
            int n = reader.getNumberOfPages();
            for (int j = 1; j <= n; j++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, j);
                copy.addPage(page);
            }
            reader.close();
        }
        copy.close();
        document.close();
        log.debug("正在刪除單個文件");
        files.forEach(e -> {
            File dateFile = new File(e);
            if (dateFile.exists()) {
                dateFile.delete();
            }
        });
    }

 

3.本地實現郵件轉換爲PDF的功能。

 

實現思路: 郵件類型先轉換成html,然後再轉換爲PDF, email -> html-> pdf

傳參數需要把content-Type= application/x-emf

核心代碼如下:



 

email轉換爲html:

 public void emlToHtml(InputStream file, String path) {
        MailMessage messageEML = MailMessage.load(file);
        messageEML.save(path, SaveOptions.getDefaultHtml());
    }

 

html轉換爲pdf:

 public void emlToPdf(InputStream file,String path) throws Exception {

        //ByteArrayInputStream 轉換爲inputstream
//        Presentation doc = new Presentation(file);
//        doc.save(path, SaveFormat.Pdf);
        emlToHtml(file,path);
        //再轉換爲PDF
        getLicense();
        Document doc = new Document(path);
        doc.save(path, SaveFormat.PDF);

//        getLicense();
//        Workbook workbook = new Workbook(file);
//        workbook.save(path, com.aspose.cells.SaveFormat.PDF);
    }

 

轉換成pdf之前需要先獲取license,即憑證:

 

 測試,如果不加license,那麼api合成的兩個pdf之間會帶有aspose水印。如下:

 

 

 

 

巨坑的地方出現啦!水印問題很大,因爲不解決,這個aspose標緻太顯眼,客戶肯定會不滿意,然後自己摸索着嘗試根據提示需要導入aspose.words的license,重新導包後,水印解決!

 

  

該License類需要是aspose.words包下才行:

同樣的方式: 先獲取到license,然後將eml轉換爲html的文件轉換爲PDF。

沒有水印的兩個郵件合成一個PDF文件出爐了!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章