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

 更新时间:2021年01月06日 10:51:38   作者:兔老大的胡萝卜  
这篇文章主要介绍了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;
 }

}

到此这篇关于springboot各种格式转pdf的文章就介绍到这了,更多相关springboot格式转pdf内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 如何提高java代码的重用性

    如何提高java代码的重用性

    在本篇文章中小编给各位分享了关于如何提高java代码的重用性的相关知识点内容,有需要的朋友们参考下。
    2019-07-07
  • Java Spring @Autowired的这些骚操作,你都知道吗

    Java Spring @Autowired的这些骚操作,你都知道吗

    这篇文章主要介绍了彻底搞明白Spring中的自动装配和Autowired注解的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2021-09-09
  • Java定时器通信协议管理模块Timer详解

    Java定时器通信协议管理模块Timer详解

    这篇文章主要介绍了Java定时器通信协议管理模块Timer, Timer一般指定时器(通信协议管理模块)人类最早使用的定时工具是沙漏或水漏,但在钟表诞生发展成熟之后,人们开始尝试使用这种全新的计时工具来改进定时器,达到准确控制时间的目的
    2022-08-08
  • Java实现超级实用的日记本

    Java实现超级实用的日记本

    一个用Java语言编写的,实现日记本的基本编辑功能、各篇日记之间的上下翻页、查询日记内容的程序。全部代码分享给大家,有需要的小伙伴参考下。
    2015-05-05
  • 详解SpringBoot自动配置源码

    详解SpringBoot自动配置源码

    今天带大家来分析SpringBoot自动配置源码,文中有非常详细的代码示例,对正在学习java的小伙伴们很有帮助,需要的朋友可以参考下
    2021-06-06
  • SpringBoot项目yml配置文件不自动提示解决方案

    SpringBoot项目yml配置文件不自动提示解决方案

    这篇文章主要介绍了SpringBoot项目配置文件.yaml/.yml文件编写时没有自动提示的解决方案,文章通过图文结合的方式给大家讲解的非常详细,需要的朋友可以参考下
    2024-06-06
  • springmvc项目使用@Valid+BindingResult遇到的问题

    springmvc项目使用@Valid+BindingResult遇到的问题

    这篇文章主要介绍了springmvc项目使用@Valid+BindingResult遇到的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • 详解Java并发编程之volatile关键字

    详解Java并发编程之volatile关键字

    这篇文章主要为大家介绍了Java并发编程之volatile关键字,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-11-11
  • Spring-Security实现登录接口流程

    Spring-Security实现登录接口流程

    Security 是 Spring 家族中的一个安全管理框架,SpringSecurity的原理其实就是一个过滤器链,内部包含了提供各种功能的过滤器,这篇文章主要介绍了Spring-Security实现登录接口,需要的朋友可以参考下
    2023-05-05
  • Android开发Kotlin实现圆弧计步器示例详解

    Android开发Kotlin实现圆弧计步器示例详解

    这篇文章主要为大家介绍了Android开发Kotlin绘制圆弧计步器示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06

最新评论