栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

添加依赖


    
      com.documents4j
      documents4j-local
      1.0.3
    
    
      com.documents4j
      documents4j-transformer-msoffice-word
      1.0.3
    

    
      com.itextpdf
      itextpdf
      5.5.10
    

测试方法

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;


public class Topdf {


  
  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();
    }
  }


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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/129553.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号