Merge pull request #15404 from wynnteo/BAEL-7278

BAEL-7278 first draft
This commit is contained in:
Maiklins 2023-12-19 22:55:48 +01:00 committed by GitHub
commit af2476da3a
4 changed files with 303 additions and 0 deletions

View File

@ -35,6 +35,21 @@
<artifactId>pdfbox</artifactId>
<version>${pdfbox.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi-ooxml.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j-api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j-core.version}</version>
</dependency>
</dependencies>
<build>
@ -52,6 +67,9 @@
<itextpdf.core.version>7.2.3</itextpdf.core.version>
<itextpdf.cleanup.version>3.0.1</itextpdf.cleanup.version>
<pdfbox.version>3.0.0</pdfbox.version>
<poi-ooxml.version>5.2.5</poi-ooxml.version>
<log4j-api.version>2.20.0</log4j-api.version>
<log4j-core.version>2.20.0</log4j-core.version>
</properties>
</project>

View File

@ -0,0 +1,242 @@
package com.baeldung.exceltopdf;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
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.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ExcelToPDFConverter {
private static final Logger logger = LogManager.getLogger(ExcelToPDFConverter.class);
public static XSSFWorkbook readExcelFile(String excelFilePath) throws IOException {
FileInputStream inputStream = new FileInputStream(excelFilePath);
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
inputStream.close();
return workbook;
}
private static Document createPDFDocument(String pdfFilePath) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(pdfFilePath));
document.open();
return document;
}
public static void convertExcelToPDF(String excelFilePath, String pdfFilePath) throws IOException, DocumentException {
XSSFWorkbook workbook = readExcelFile(excelFilePath);
Document document = createPDFDocument(pdfFilePath);
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
XSSFSheet worksheet = workbook.getSheetAt(i);
// Add header with sheet name as title
Paragraph title = new Paragraph(worksheet.getSheetName(), new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD));
title.setSpacingAfter(20f);
title.setAlignment(Element.ALIGN_CENTER);
document.add(title);
createAndAddTable(worksheet, document);
// Add a new page for each sheet (except the last one)
if (i < workbook.getNumberOfSheets() - 1) {
document.newPage();
}
}
document.close();
workbook.close();
}
private static void createAndAddTable(XSSFSheet worksheet, Document document) throws DocumentException, IOException {
PdfPTable table = new PdfPTable(worksheet.getRow(0)
.getPhysicalNumberOfCells());
table.setWidthPercentage(100);
addTableHeader(worksheet, table);
addTableData(worksheet, table);
document.add(table);
}
private static void addTableHeader(XSSFSheet worksheet, PdfPTable table) throws DocumentException, IOException {
Row headerRow = worksheet.getRow(0);
for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
Cell cell = headerRow.getCell(i);
String headerText = getCellText(cell);
PdfPCell headerCell = new PdfPCell(new Phrase(headerText, getCellStyle(cell)));
setBackgroundColor(cell, headerCell);
setCellAlignment(cell, headerCell);
table.addCell(headerCell);
}
}
public static String getCellText(Cell cell) {
String cellValue;
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
cellValue = String.valueOf(BigDecimal.valueOf(cell.getNumericCellValue()));
break;
case BLANK:
default:
cellValue = "";
break;
}
return cellValue;
}
private static void addTableData(XSSFSheet worksheet, PdfPTable table) throws DocumentException, IOException {
Iterator<Row> rowIterator = worksheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
if (row.getRowNum() == 0) {
continue;
}
for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {
Cell cell = row.getCell(i);
String cellValue = getCellText(cell);
PdfPCell cellPdf = new PdfPCell(new Phrase(cellValue, getCellStyle(cell)));
setBackgroundColor(cell, cellPdf);
setCellAlignment(cell, cellPdf);
table.addCell(cellPdf);
}
}
}
private static void setBackgroundColor(Cell cell, PdfPCell cellPdf) {
// Set background color
short bgColorIndex = cell.getCellStyle()
.getFillForegroundColor();
if (bgColorIndex != IndexedColors.AUTOMATIC.getIndex()) {
XSSFColor bgColor = (XSSFColor) cell.getCellStyle()
.getFillForegroundColorColor();
if (bgColor != null) {
byte[] rgb = bgColor.getRGB();
if (rgb != null && rgb.length == 3) {
cellPdf.setBackgroundColor(new BaseColor(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF));
}
}
}
}
private static void setCellAlignment(Cell cell, PdfPCell cellPdf) {
CellStyle cellStyle = cell.getCellStyle();
HorizontalAlignment horizontalAlignment = cellStyle.getAlignment();
VerticalAlignment verticalAlignment = cellStyle.getVerticalAlignment();
switch (horizontalAlignment) {
case LEFT:
cellPdf.setHorizontalAlignment(Element.ALIGN_LEFT);
break;
case CENTER:
cellPdf.setHorizontalAlignment(Element.ALIGN_CENTER);
break;
case JUSTIFY:
case FILL:
cellPdf.setVerticalAlignment(Element.ALIGN_JUSTIFIED);
break;
case RIGHT:
cellPdf.setHorizontalAlignment(Element.ALIGN_RIGHT);
break;
}
switch (verticalAlignment) {
case TOP:
cellPdf.setVerticalAlignment(Element.ALIGN_TOP);
break;
case CENTER:
cellPdf.setVerticalAlignment(Element.ALIGN_MIDDLE);
break;
case JUSTIFY:
cellPdf.setVerticalAlignment(Element.ALIGN_JUSTIFIED);
break;
case BOTTOM:
cellPdf.setVerticalAlignment(Element.ALIGN_BOTTOM);
break;
}
}
private static Font getCellStyle(Cell cell) throws DocumentException, IOException {
Font font = new Font();
CellStyle cellStyle = cell.getCellStyle();
org.apache.poi.ss.usermodel.Font cellFont = cell.getSheet()
.getWorkbook()
.getFontAt(cellStyle.getFontIndexAsInt());
short fontColorIndex = cellFont.getColor();
if (fontColorIndex != IndexedColors.AUTOMATIC.getIndex() && cellFont instanceof XSSFFont) {
XSSFColor fontColor = ((XSSFFont) cellFont).getXSSFColor();
if (fontColor != null) {
byte[] rgb = fontColor.getRGB();
if (rgb != null && rgb.length == 3) {
font.setColor(new BaseColor(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF));
}
}
}
if (cellFont.getItalic()) {
font.setStyle(Font.ITALIC);
}
if (cellFont.getStrikeout()) {
font.setStyle(Font.STRIKETHRU);
}
if (cellFont.getUnderline() == 1) {
font.setStyle(Font.UNDERLINE);
}
short fontSize = cellFont.getFontHeightInPoints();
font.setSize(fontSize);
if (cellFont.getBold()) {
font.setStyle(Font.BOLD);
}
String fontName = cellFont.getFontName();
if (FontFactory.isRegistered(fontName)) {
font.setFamily(fontName); // Use extracted font family if supported by iText
} else {
logger.warn("Unsupported font type: {}", fontName);
// - Use a fallback font (e.g., Helvetica)
font.setFamily("Helvetica");
}
return font;
}
public static void main(String[] args) throws DocumentException, IOException {
String excelFilePath = "src/main/resources/excelsample.xlsx";
String pdfFilePath = "src/main/resources/pdfsample.pdf";
convertExcelToPDF(excelFilePath, pdfFilePath);
}
}

Binary file not shown.

View File

@ -0,0 +1,43 @@
%PDF-1.4
%âãÏÓ
3 0 obj
<</Length 751/Filter/FlateDecode>>stream
xœ•WËRÛ0Ýû+î’.Puõ´@Ÿ”R žÎtéi ¤Íc0d:ü}%K&a¢«<C2A2>daœãsïÑtdªÓ¦’jn ™VXæ, îÞšÛêèG?íz¸˜=>ÁU{×¾kþTÇéqÚyÞðç høe¸çpŒj¨ÿ±©®«‡Š3'œBàL9.ü<05>@ý]<5D>b}säŠ<19>ú®º-<ŽŠ³ÃBi&bHåX}CiÅT††.àÜûñÙ³5üË w üÐF4?ŒÍKѼ¼É–$îägW<12>&Iš$hDq 'GÈìJ¢Ð(‰B£$
<EFBFBD>H®ojGȯú]Iš$hD IÅõMµ-¹D I<12>&Iš$Q\ßÔï<C394>$M4I"Ð$‰âú¦øb`fyShD I<12>&I;èuH_Ÿ þ‹`-ãaK;h1zUˆ^3\×5„+:órõ9st¹b!i9Ü…dݪ…F±ÚV,Fü×ùŠ"T”`•|{ųõãÓjÑõcÅ—Z¶fJ<66>êŠl]^<5E>¬5“õa#lVOí<_N9ôq~X¹«v6¥Ä<C2A5>EŒ• * Xà!ãĬ)òu©^3O<33>û3¤lÈ_ºïÉrú íšp@8Æu‰¯ «ó\ͳ%ê/Ò'ã4E
Ìè“(ùT`ŸwËå3|Y}*ðýêv´¸´Q$É=F<>Ì<EFBFBD> 9£dÑ(ºïÅzö?)ÛV<C39B><EFBFBD>mÀ÷úD·.ø¤ER{|¢™Ñ'Uô‰fë¼*/(í^;åQfâ¥DéýaOH¦K{° ¢°ÇPÏìùWÅßoÂÛk=˜ƒmÒÁ¢BçÕªáfÎ=ÿŠ‹þ‘]“é^ÑdbxÉdšý½]®»9Lœ¶7gNÞkºŒÙrjÁ`$²yƒÁ>W7û²Át¯h°)þó˳ÏîÛ~>ëà†íœç‘o“ß÷};Ý7´Li*hêöTüˆ
endstream
endobj
5 0 obj
<</Type/Page/MediaBox[0 0 595 842]/Resources<</Font<</F1 1 0 R/F2 2 0 R>>>>/Contents 3 0 R/Parent 4 0 R>>
endobj
1 0 obj
<</Type/Font/Subtype/Type1/BaseFont/Helvetica-Bold/Encoding/WinAnsiEncoding>>
endobj
2 0 obj
<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>
endobj
4 0 obj
<</Type/Pages/Count 1/Kids[5 0 R]>>
endobj
6 0 obj
<</Type/Catalog/Pages 4 0 R>>
endobj
7 0 obj
<</Producer(iText® 5.5.13.3 ©2000-2022 iText Group NV \(AGPL-version\))/CreationDate(D:20231213174247+08'00')/ModDate(D:20231213174247+08'00')>>
endobj
xref
0 8
0000000000 65535 f
0000000954 00000 n
0000001047 00000 n
0000000015 00000 n
0000001135 00000 n
0000000833 00000 n
0000001186 00000 n
0000001231 00000 n
trailer
<</Size 8/Root 6 0 R/Info 7 0 R/ID [<6a28b1036b62f3808f3bfb62a88a5239><6a28b1036b62f3808f3bfb62a88a5239>]>>
%iText-5.5.13.3
startxref
1391
%%EOF