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内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 基于SpringBoot框架管理Excel和PDF文件类型

    一.文档类型简介 1.Excel文档 Excel一款电子表格软件.直观的界面.出色的计算功能和图表工具,在系统开发中,经常用来把数据转存到Excel文件,或者Excel数据导入系统中,这就涉及数据转换问题. 2.PDF文档 PDF是可移植文档格式,是一种电子文件格式,具有许多其他电子文档格式无法相比的优点.PDF文件格式可以将文字.字型.格式.颜色及独立于设备和分辨率的图形图像等封装在一个文件中.该格式文件还可以包含超文本链接.声音和动态影像等电子信息,支持特长文件,集成度和安全可靠性都较高.

  • SpringBoot日期格式转换之配置全局日期格式转换器的实例详解

    1. SpringBoot设置后台向前台传递Date日期格式 在springboot应用中,@RestController注解的json默认序列化中,日期格式默认为:2020-12-03T15:12:26.000+00:00类型的显示. 在实际显示中,我们需要对其转换成我们需要的显示格式. 1.1 方式1:配置文件修改 配置文件配置application.yml: spring: # 配置日期格式化 jackson: date-format: yyyy-MM-dd HH:mm:ss #时间戳统一

  • 详解json在SpringBoot中的格式转换

    @RestController自动返回json /** * json 三种实现方法 * 1 @RestController自动返回json */ @GetMapping("/json") public Student getjson() { Student student = new Student("bennyrhys",158 ); return student; } @ResponseBody+@Controller 组合返回json //@RestContr

  • Spring Boot 将yyyy-MM-dd格式的文本字符串直接转换为LocalDateTime出现的问题

    Spring Boot 将yyyy-MM-dd格式的文本字符串直接转换为LocalDateTime出现的问题 问题复现 Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-03-12' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2020-

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

    添加依赖 <!--转pdf--> <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-local</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>com.documents4j</

  • C#添加、获取、删除PDF附件实例代码

    概述 附件,指随同文件发出的有关文件或物品.在PDF文档中,我们可以添加同类型的或其他类型的文档作为附件内容,而PDF中附件也可以分为两种存在形式,一种是附件以普通文件形式存在,另一种是以注释的形式存在.在下面的示例中介绍了如何分别添加以上两种形式的PDF附件.此外,根据PDF附件的不同添加方式,我们在获取PDF附件信息或删除PDF附件时,也可以分情况来执行操作. 工具使用 pire.PDF for .NET 4.0 代码示例(供参考)  1.添加PDF附件    1.1 以普通文档形式添加附件

  • SpringBoot创建JSP登录页面功能实例代码

    添加JSP配置 1.pom.xml添加jsp解析引擎 <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.s

  • springboot 中文件上传下载实例代码

    Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者. Spring Boot特点 1. 创建独立的Spring应用程序 2. 嵌入的Tomcat,无需部署WAR文件 3. 简化Maven配置 4. 自动配置Spr

  • java实现输出文件夹下某个格式的所有文件实例代码

    package file; import java.io.File; /** * 输出某个文件夹下所有某个格式的文件 * @author hasee * */ public class Demo2 { public static void main(String[] args) { getTxtName("d:/a",".jpg"); } public static void getTxtName(String path,String suffix) { //判断文

  • 使用java文件过滤器输出制定格式文件路径的实例代码

    使用java文件过滤器输出制定格式文件路径的实例代码如下所示: 一.使用输出路径判断过滤 import java.io.File; public class demo_file04 { public static void main(String[] args) { fileall(new File("D:\\coding")); } private static void fileall(File f1) { // System.out.println(f1); //判断文件是否是目

  • springBoot+webMagic实现网站爬虫的实例代码

    前端时间公司项目需要抓取各类数据,py玩的不6,只好研究Java爬虫方案,做一个总结. 开发环境: springBoot 2.2.6.jdk1.8. 1.导入依赖 <!--WebMagic核心包--> <dependency> <groupId>us.codecraft</groupId> <artifactId>webmagic-core</artifactId> <version>0.7.3</version&g

  • SpringBoot使用Thymeleaf自定义标签的实例代码

    此篇文章内容仅限于 描述springboot与 thy 自定义标签的说明,所以你在看之前,请先会使用springboot和thymeleaf!! 之前写过一篇是springMVC与thymeleaf 的自定义标签(属于自定义方言的属性一块,类似thy的th:if和th:text等)文章,如果你想了解,以下是地址: 点击>>Thymeleaf3.0自定义标签属性 这篇例子可以实现你的分页标签实现等功能,不会讲一堆的废话和底层的原理(自行百度),属于快速上手教程,请认真看以下内容! PS: 请允许

  • Java把数字格式化为货币字符串实例代码

    数字可以标志货币.百分比.积分和电话号码等,就货币而言,在不同的国家会以不同的格式来定义,本实例将接收用户输入的数字,然后在控制台中输出其货币格式,其中使用了不同国家的货币格式. 思路如下:使用NumberFormat类的getCurrencyInstance()方法,通过不同的参数创建不同的对象,对该对象使用format()方法,方法参数即为用户输入的数字. 代码如下: 复制代码 代码如下: import java.text.NumberFormat;import java.util.Loca

  • 将Python字符串生成PDF的实例代码详解

    笔者在今天的工作中,遇到了一个需求,那就是如何将Python字符串生成PDF.比如,需要把Python字符串'这是测试文件'生成为PDF, 该PDF中含有文字'这是测试文件'.   经过一番检索,笔者决定采用wkhtmltopdf这个软件,它可以将HTML转化为PDF.wkhtmltopdf的访问网址为:https://wkhtmltopdf.org/downloads.html ,读者可根据自己的系统下载对应的文件并安装.安装好wkhtmltopdf,我们再安装这个软件的Python第三方模块

随机推荐