package com.ruoyi.common.utils; import com.itextpdf.text.Image; import com.itextpdf.text.pdf.PdfWriter; import com.ruoyi.common.utils.file.FileUtils; import com.spire.doc.Document; import com.spire.doc.FileFormat; import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfDocumentBase; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @Configuration public class MergeFilesToPDFUtils { @Value("${ruoyi.archived}") private String archived; /** * 将图片合成pdf */ public Boolean addImageToPdf(String imagePath, String pdfPath) throws IOException { com.itextpdf.text.Document document = new com.itextpdf.text.Document(); try { PdfWriter.getInstance(document, new FileOutputStream(pdfPath)); document.open(); // 获取图像的宽度和高度 BufferedImage image = ImageIO.read(new File(imagePath)); float imageWidth = image.getWidth(); float imageHeight = image.getHeight(); // 获取页面的宽度和高度 float pageWidth = document.getPageSize().getWidth(); float pageHeight = document.getPageSize().getHeight(); // 计算调整比例,确保图像适应页面 float widthRatio = pageWidth / imageWidth; float heightRatio = pageHeight / imageHeight; float ratio = Math.min(widthRatio, heightRatio); // 计算调整后的图像大小 float adjustedWidth = imageWidth * ratio - 50; float adjustedHeight = imageHeight * ratio - 50; // 创建图像对象 Image pdfImage = Image.getInstance(imagePath); pdfImage.scaleAbsolute(adjustedWidth, adjustedHeight); // 添加图像到文档 document.add(pdfImage); } catch (Exception e) { e.printStackTrace(); } finally { document.close(); } return true; } /** * WORD转PDF * * @param inputPath * @param outputPath */ public Boolean wordtoPdf(String inputPath, String outputPath) { Document doc = new Document(); //加载Word doc.loadFromFile(inputPath); //保存为PDF格式 doc.saveToFile(outputPath, FileFormat.PDF); return true; } /** * pdf合并 */ public Boolean mergePDF(String[] pdfFiles, String fileName, HttpServletResponse response) { try { PdfDocumentBase pdf = PdfDocument.mergeFiles(pdfFiles); //Save the result to a PDF file pdf.save(archived + fileName, com.spire.pdf.FileFormat.PDF); String filePath = archived + fileName; response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); FileUtils.setAttachmentResponseHeader(response, fileName); FileUtils.writeBytes(filePath, response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }