1. 程式人生 > 程式設計 >springboot各種格式轉pdf的例項程式碼

springboot各種格式轉pdf的例項程式碼

新增依賴

<!--轉pdf-->
    <dependency>
      <groupId>com.documents4j</groupId>
      <artifactId>documents4j-local</artifactId>
      <version>1.0.3</version>
    </dependency>
    <dependency>
      <groupId>com.documents4j</groupId>
      <artifactId>documents4j-transformer-msoffice-word</artifactId>
      <version>1.0.3</version>
    </dependency>

    <dependency>
      <groupId>com.itextpdf</groupId>
      <artifactId>itextpdf</artifactId>
      <version>5.5.10</version>
    </dependency>

測試方法

package com.ruoyi.mlogin.util;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.*;
import java.net.MalformedURLException;

/**
 * @author cai
 * @version 1.0
 * @date 2021/1/4 14:58
 */
public class Topdf {


  /**
   * 轉pdf doc docx xls xlsx
   * @param path
   */
  public void docTopdf(String path) {

    File inputWord = new File("C:\\Users\\29934\\Documents\\Tencent Files\\2993481541\\FileRecv\\1111.docx");
    File outputFile = new File("C:\\Users\\29934\\Documents\\Tencent Files\\2993481541\\FileRecv\\1111.pdf");
    try {
      InputStream docxInputStream = new FileInputStream(inputWord);
      OutputStream outputStream = new FileOutputStream(outputFile);
      IConverter converter = LocalConverter.builder().build();
      String fileTyle=path.substring(path.lastIndexOf("."),path.length());//獲取檔案型別
      if(".docx".equals(fileTyle)){
        converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
      }else if(".doc".equals(fileTyle)){
        converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
      }else if(".xls".equals(fileTyle)){
        converter.convert(docxInputStream).as(DocumentType.XLS).to(outputStream).as(DocumentType.PDF).execute();
      }else if(".xlsx".equals(fileTyle)){
        converter.convert(docxInputStream).as(DocumentType.XLSX).to(outputStream).as(DocumentType.PDF).execute();
      }
      outputStream.close();
      System.out.println("pdf轉換成功");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  /**
   *
   *      生成pdf檔案
   *      需要轉換的圖片路徑的陣列
   */
  public static void main(String[] args) {
    try {
      String imagesPath = "C:\\Users\\29934\\Documents\\Tencent Files\\2993481541\\FileRecv\\1111.jpg";
      File file = new File("C:\\Users\\29934\\Documents\\Tencent Files\\2993481541\\FileRecv\\1111.pdf");
      // 第一步:建立一個document物件。
      Document document = new Document();
      document.setMargins(0,0);
      // 第二步:
      // 建立一個PdfWriter例項,
      PdfWriter.getInstance(document,new FileOutputStream(file));
      // 第三步:開啟文件。
      document.open();
      // 第四步:在文件中增加圖片。
      if (true) {
        Image img = Image.getInstance(imagesPath);
        img.setAlignment(Image.ALIGN_CENTER);
        // 根據圖片大小設定頁面,一定要先設定頁面,再newPage(),否則無效
        document.setPageSize(new Rectangle(img.getWidth(),img.getHeight()));
        document.newPage();
        document.add(img);
        //下面是對應一個資料夾的圖片
//      File files = new File(imagesPath);
//      String[] images = files.list();
//      int len = images.length;
//
//      for (int i = 0; i < len; i++)
//      {
//        if (images[i].toLowerCase().endsWith(".bmp")
//            || images[i].toLowerCase().endsWith(".jpg")
//            || images[i].toLowerCase().endsWith(".jpeg")
//            || images[i].toLowerCase().endsWith(".gif")
//            || images[i].toLowerCase().endsWith(".png")) {
//          String temp = imagesPath + "\\" + images[i];
//          Image img = Image.getInstance(temp);
//          img.setAlignment(Image.ALIGN_CENTER);
//          // 根據圖片大小設定頁面,一定要先設定頁面,再newPage(),否則無效
//          document.setPageSize(new Rectangle(img.getWidth(),img.getHeight()));
//          document.newPage();
//          document.add(img);
//        }
//      }
        // 第五步:關閉文件。
        document.close();
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (BadElementException e) {
      e.printStackTrace();
    } catch (DocumentException e) {
      e.printStackTrace();
    }
  }

}

補充:下面看下springboot:擴充套件型別轉換器

需求:提交一個字串到後端的java.sql.Time型別,就報錯了:

Failed to convert property value of type [java.lang.String] to required type [java.sql.Time]

正常提交到java.util.Date型別是沒有問題的。

所以這裡就需要擴充套件內建的springmvc的轉換器

程式碼如下:

WebConfig : 新增新的型別轉換器

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import com.csget.web.converter.StringToTimeConverter;

@Configuration
public class WebConfig {

 @Autowired
 private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

 @PostConstruct
 public void addConversionConfig() {
  ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter
    .getWebBindingInitializer();
  if (initializer.getConversionService() != null) {
   GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
   genericConversionService.addConverter(new StringToTimeConverter());
  }
 }
}

StringToTimeConverter :型別轉換器的具體實現

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

public class StringToTimeConverter implements Converter<String,Time> {
 public Time convert(String value) {
  Time time = null;
  if (StringUtils.isNotBlank(value)) {
   String strFormat = "HH:mm";
   int intMatches = StringUtils.countMatches(value,":");
   if (intMatches == 2) {
    strFormat = "HH:mm:ss";
   }
   SimpleDateFormat format = new SimpleDateFormat(strFormat);
   Date date = null;
   try {
    date = format.parse(value);
   } catch (Exception e) {
    e.printStackTrace();
   }
   time = new Time(date.getTime());
  }
  return time;
 }

}

到此這篇關於springboot各種格式轉pdf的文章就介紹到這了,更多相關springboot格式轉pdf內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!