• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

springboot 搞代码 4年前 (2022-01-05) 41次浏览 已收录 0个评论

这篇文章主要介绍了springboot各种格式转pdf的实例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

添加依赖

 <!--转pdf--> com.documents4jdocuments4j-local1.0.3 com.documents4jdocuments4j-transformer-msoffice-word1.0.3 com.itextpdfitextpdf5.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; /** * @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-600"; File file = new File("C:\\Users\\29934\\Documents\\Tencent Files\\2993481541\\FileRecv\\1111.pdf"); // 第一步:创建一个document对象。 Document document = new Document(); docume<strong style="color:transparent">来源gaodai#ma#com搞@代~码网</strong>nt.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-600") //            || images[i].toLowerCase().endsWith(".jpeg") //            || images[i].toLowerCase().endsWith(".gif") //            || images[i].toLowerCase().endsWith(".png-600")) { //          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的实例代码的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:springboot各种格式转pdf的实例代码

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址