【excel图文转pdf 如何解决? java来实现】

目录

🍭前言:

🍭excel图文转pdf:

使用到的依赖:


🍭前言:

    实战场景中总是遇见奇怪需求 ,记录一下

🍭excel图文转pdf:

  1. 使用try-with-resources语句来自动关闭文件流和PDF文档对象。

  2. 将处理图片的代码提取到一个单独的方法中,以提高代码的可读性和可维护性。

  3. 使用Java 8的Stream API来简化代码。

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.stream.IntStream;
import javax.imageio.ImageIO;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFGraphicFrame;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class ExcelToPdfDemo {
    public static void main(String[] args) {
        try (Workbook workbook = WorkbookFactory.create(new File("example.xlsx"));
             FileOutputStream fos = new FileOutputStream("example.pdf");
             Document document = new Document(PageSize.A4, 50, 50, 50, 50);
             PdfWriter writer = PdfWriter.getInstance(document, fos)) {
            document.open();
            for (Sheet sheet : workbook) {
                PdfPTable table = new PdfPTable(sheet.getRow(0).getLastCellNum());
                table.setHeaderRows(1);
                table.setWidths(IntStream.range(0, sheet.getRow(0).getLastCellNum()).mapToDouble(i -> 1).toArray());
                table.setWidthPercentage(100);
                Paragraph title = new Paragraph(sheet.getSheetName(), new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 16, Font.BOLD));
                title.setAlignment(Element.ALIGN_CENTER);
                document.add(title);
                sheet.forEach(row -> {
                    IntStream.range(0, row.getLastCellNum()).forEach(i -> {
                        Cell cell = row.getCell(i);
                        PdfPCell pdfCell = new PdfPCell(new Paragraph(cell.getStringCellValue(), new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 12)));
                        pdfCell.setBorderWidth(1f);
                        pdfCell.setBorderColor(BaseColor.BLACK);
                        pdfCell.setPadding(5f);
                        if (row.getRowNum() == 0) {
                            pdfCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                        }
                        table.addCell(pdfCell);
                        if (cell.getCellType() == CellType.BLANK || cell.getCellType() == CellType.FORMULA || cell.getCellType() == CellType.ERROR || cell.getCellType() == CellType.STRING && cell.getStringCellValue().trim().isEmpty() || cell.getCellType() == CellType.NUMERIC && cell.getNumericCellValue() == 0 || cell.getCellType() == CellType.BOOLEAN && !cell.getBooleanCellValue() || cell.getCellType() == CellType.STRING && cell.getStringCellValue().startsWith("#") || cell.getCellType() == CellType.FORMULA && cell.getCellFormula().startsWith("#") || cell.getCellType() == CellType.STRING && cell.getStringCellValue().startsWith("=") || cell.getCellType() == CellType.FORMULA && cell.getCellFormula().startsWith("=") || cell.getCellType() == CellType.STRING && cell.getStringCellValue().startsWith("@") || cell.getCellType() == CellType.FORMULA && cell.getCellFormula().startsWith("@") || cell.getCellType() == CellType.STRING && cell.getStringCellValue().startsWith("'") || cell.getCellType() == CellType.FORMULA && cell.getCellFormula().startsWith("'")) {
                            return;
                        }
                        if (cell.getCellType() == CellType.STRING && cell.getStringCellValue().startsWith("http")) {
                            try {
                                BufferedImage image = ImageIO.read(new URL(cell.getStringCellValue()));
                                if (image != null) {
                                    addImageToTable(table, image);
                                }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (sheet instanceof XSSFSheet) {
                            XSSFSheet xssfSheet = (XSSFSheet) sheet;
                            XSSFDrawing drawing = xssfSheet.createDrawingPatriarch();
                            for (XSSFShape shape : drawing.getShapes()) {
                                if (shape instanceof XSSFClientAnchor) {
                                    XSSFClientAnchor anchor = (XSSFClientAnchor) shape.getAnchor();
                                    if (anchor.getRow1() == cell.getRowIndex() && anchor.getCol1() == cell.getColumnIndex()) {
                                        if (shape instanceof XSSFGraphicFrame) {
                                            XSSFGraphicFrame frame = (XSSFGraphicFrame) shape;
                                            BufferedImage image = frame.getGraphic().getBufferedImage();
                                            addImageToTable(table, image);
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            });
            table.setSpacingBefore(20f);
            table.setSpacingAfter(20f);
            table.setKeepTogether(true);
            document.add(table);
        }
        document.close();
    } catch (IOException | DocumentException e) {
        e.printStackTrace();
    }
}

private static void addImageToTable(PdfPTable table, BufferedImage image) throws IOException, DocumentException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    baos.flush();
    byte[] imageData = baos.toByteArray();
    baos.close();
    Image pdfImage = Image.getInstance(imageData);
    pdfImage.scaleToFit(100f, 100f);
    PdfPCell imageCell = new PdfPCell(pdfImage, true);
    imageCell.setBorderWidth(1f);
    imageCell.setBorderColor(BaseColor.BLACK);
    imageCell.setPadding(5f);
    table.addCell(imageCell);
}
  •  在上面的代码中,我们使用了try-with-resources语句来自动关闭文件流和PDF文档对象。我们还将处理图片的代码提取到了一个单独的方法中 

使用到的依赖:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>
<dependency>
    <groupId>javax.media</groupId>
    <artifactId>jai_core</artifactId>
    <version>1.1.3</version>
</dependency>
Java Advanced Imaging API(JAI)库:用于处理图片。
iText库:用于创建和操作PDF文件。
Apache POI库:用于读取和写入Excel文件。
Apache Commons IO库:用于处理文件和流。
Apache Commons Lang库:用于处理字符串和其他通用操作。
Bouncy Castle库:用于处理加密和解密操作。
XML Graphics Commons库:用于处理SVG图像。
<dependency>
    <groupId>org.apache.xmlgraphics</groupId>
    <artifactId>xmlgraphics-commons</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.68</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是汤圆丫

怎么 给1分?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值