springboot各种格式转pdf的实例代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

springboot各种格式转pdf的实例代码

兔老大的胡萝卜   2021-01-06 我要评论
这篇文章主要介绍了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, 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;
 }

}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们