复制到自己的项目直接调用使用!
1.需要在pom.xml中增加:
<!-- PDF-PNG-Apache PDFBox-->
<dependency>
<groupId>net.sf.cssbox</groupId>
<artifactId>pdf2dom</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.27</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.27</version>
</dependency>
<!--word转换为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>
wholeIsPngUtil类
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.ruoyi.common.enums.LibFileExtEnum;
import com.ruoyi.system.service.CloudStorageService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.xslf.usermodel.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class wholeIsPngUtil {
/**
* @param fileType 约定文件类型 1-PDF 2-doc/docx 3-ppt/pptx
* @param fileUrl 网络地址
* @param cloudStorageService 上传service(此service是我转成PNG后上传到oss的,你们可以根据自己的需要修改)
* @return
*/
public static List<String> getViewImageList(Integer fileType, String fileUrl, CloudStorageService cloudStorageService) {
List<String> list = new ArrayList<>();
switch (fileType) {
case 1:
list = pdfToPNG(cloudStorageService, fileUrl);
break;
case 2:
list = wordToPNG(cloudStorageService, fileUrl);
break;
case 3:
list = pptToPNG(cloudStorageService, fileUrl);
break;
default:
break;
}
return list;
}
private static String getImageStoreDir() {
return LibFileExtEnum.IMAGE_PNG.getStoreDir();
}
/**
*
* @param url 网络地址
*/
public static List<String> pdfToPNG(CloudStorageService cloudStorageService, String url) {
List<String> list = new ArrayList<>();
long startTime = System.currentTimeMillis();
try {
URL pdfUrl = new URL(url);
PDDocument pdDocument = PDDocument.load(pdfUrl.openStream());
PDFRenderer renderer = new PDFRenderer(pdDocument);
//总页数
int pageCount = pdDocument.getNumberOfPages();
for (int i = 0; i < pageCount; i++) {
// dpi越高越清晰,转换越慢
BufferedImage image = renderer.renderImageWithDPI(i, 70); // Windows native DPI
// 将图片写出到该路径下
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
String[] onlineUrls = cloudStorageService.upload(imageInByte, getImageStoreDir(), ".png");
list.addAll(Arrays.asList(onlineUrls[1]));
}
long endTime = System.currentTimeMillis();
System.out.println("pdfToPng共耗时:" + ((endTime - startTime) / 1000.0) + "秒"); // 转换用时
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
*
* @param url 文件地址
*/
public static List<String> wordToPNG(CloudStorageService cloudStorageService, String url) {
List<String> list = new ArrayList<>();
// 将文件地址和文件名拼接成路径 注意:线上环境不能使用\\拼接 // 获取word文档
try {
URL wordUrl = new URL(url);
long startTime = System.currentTimeMillis();
// 打开生成的 Word 文件
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//word转pdf
convertWordToPdf(wordUrl.openStream(),baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
ByteArrayInputStream inputStream =new ByteArrayInputStream(imageInByte);
PDDocument pdDocument = PDDocument.load(inputStream);
PDFRenderer renderer = new PDFRenderer(pdDocument);
//总页数
int pageCount = pdDocument.getNumberOfPages();
for (int i = 0; i < pageCount; i++) {
// dpi越高越清晰,转换越慢
BufferedImage image = renderer.renderImageWithDPI(i, 70); // Windows native DPI
// 将图片写出到该路径下
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos1);
baos1.flush();
byte[] imageInByte1 = baos1.toByteArray();
baos1.close();
String[] onlineUrls = cloudStorageService.upload(imageInByte1, getImageStoreDir(), ".png");
list.addAll(Arrays.asList(onlineUrls[1]));
}
long endTime = System.currentTimeMillis();
System.out.println("WordToPNG共耗时:" + ((endTime - startTime) / 1000.0) + "秒"); // 转换用时
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
/**
* word转pdf
*
*/
public static void convertWordToPdf(InputStream stream, ByteArrayOutputStream sourceOutput) {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
// Windows操作系统
windowsWordToPdf(stream,sourceOutput);
} else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
System.out.println("读取操作系统");
// Unix/Linux/Mac操作系统
linuxWordToPdf(stream,sourceOutput);
} else {
// 未知操作系统
throw new RuntimeException("不支持当前操作系统转换文档。");
}
}
/**
* 通过documents4j 实现word转pdf -- Windows 环境 需要有 Microsoft Office 服务
*
*/
public static void windowsWordToPdf(InputStream stream, ByteArrayOutputStream sourceOutput) {
try{
IConverter converter = LocalConverter.builder().build();
converter.convert(stream)
.as(DocumentType.DOCX)
.to(sourceOutput)
.as(DocumentType.PDF).execute();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通过libreoffice 实现word转pdf -- linux 环境 需要有 libreoffice 服务
*
*/
public static void linuxWordToPdf(InputStream stream,ByteArrayOutputStream sourceOutput) {
// 创建临时文件
File tempFile = createTempFileFromInputStream(stream);
// 构建LibreOffice的命令行工具命令
String command = "libreoffice --headless --invisible --convert-to pdf " + tempFile.getAbsolutePath() + " --outdir " + tempFile.getParent();
System.out.println("转换"+command);
// 执行转换命令
try {
if (!executeLinuxCmd(command)) {
System.out.println("转换失败");
throw new IOException("转换失败");
}
readPdfFileToByteArrayOutputStream(tempFile,sourceOutput);
} catch (Exception e) {
// 清理临时文件
System.out.println("清理成功");
// tempFile.delete();
} finally {
File pdfFile = new File(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
System.out.println("PDF文件目录"+pdfFile.getPath()+"===="+pdfFile);
//清理转换后的pdf文件
pdfFile.delete();
// 清理临时文件,无论是否成功转换
tempFile.delete();
}
}
/**
* 执行命令行
*
* @param cmd 命令行
* @return
* @throws IOException
*/
private static boolean executeLinuxCmd(String cmd) throws IOException {
Process process = Runtime.getRuntime().exec(cmd);
try {
process.waitFor();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
return true;
}
/**
*
* 创建临时文件
*/
private static File createTempFileFromInputStream(InputStream inputStream) {
try {
File tempFile = File.createTempFile("temp_word", ".docx");
Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("创建临时文件目录:"+tempFile.getPath() +"====="+tempFile +"=====");
return tempFile;
} catch (IOException e) {
throw new RuntimeException("创建临时文件失败", e);
}
}
/**
* 读取pdf文件
*/
private static void readPdfFileToByteArrayOutputStream(File tempFile,ByteArrayOutputStream sourceOutput){
try {
Path outputFile = Paths.get(tempFile.getParent(), tempFile.getName().replace(".docx", ".pdf"));
Files.copy(outputFile, sourceOutput);
System.out.println("读取临时文件:"+"====="+tempFile.getParent());
} catch (Exception e) {
System.out.println("读取临时文件失败:"+"====="+tempFile.getParent());
throw new RuntimeException(e);
}
}
/**
* 自由确定起始页和终止页
*
* @param url 文件地址
*/
public static List<String> pptToPNG(CloudStorageService cloudStorageService, String url) {
List<String> list = new ArrayList<>();
long startTime = System.currentTimeMillis();
try {
URL wordUrl = new URL(url);
XMLSlideShow xmlSlideShow = new XMLSlideShow(wordUrl.openStream());
// 获取大小
Dimension pgsize = xmlSlideShow.getPageSize();
//总页数
int size = xmlSlideShow.getSlides().size();
// 获取幻灯片
List<XSLFSlide> slides = xmlSlideShow.getSlides();
for (int i = 0; i < size; i++) {
// 解决乱码问题
List<XSLFShape> shapes1 = slides.get(i).getShapes();
for (XSLFShape shape : shapes1) {
if (shape instanceof XSLFTextShape) {
XSLFTextShape sh = (XSLFTextShape) shape;
List<XSLFTextParagraph> textParagraphs = sh.getTextParagraphs();
for (XSLFTextParagraph xslfTextParagraph : textParagraphs) {
List<XSLFTextRun> textRuns = xslfTextParagraph.getTextRuns();
for (XSLFTextRun xslfTextRun : textRuns) {
xslfTextRun.setFontFamily("宋体");
}
}
}
}
//根据幻灯片大小生成图片
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D graphics = img.createGraphics();
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// 最核心的代码
slides.get(i).draw(graphics);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 写入到图片中去
ImageIO.write(img, "png", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
String[] onlineUrls = cloudStorageService.upload(imageInByte, getImageStoreDir(), ".png");
list.addAll(Arrays.asList(onlineUrls[1]));
}
long endTime = System.currentTimeMillis();
System.out.println("pptToPNG共耗时:" + ((endTime - startTime) / 1000.0) + "秒"); // 转换用时
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}