-
Notifications
You must be signed in to change notification settings - Fork 11
feat: added a spreadsheet to PDF converter for Excel files with MIME … #940
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
konradlang
wants to merge
9
commits into
master
Choose a base branch
from
939-feature-convert-spreadsheets-excel-to-pdf-and-include-in-merged-pdf
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
249a886
feat: added a spreadsheet to PDF converter for Excel files with MIME …
konradlang 6ba859b
Additional tests to enhance test coverage.
konradlang 99a7303
Merge branch 'master' into 939-feature-convert-spreadsheets-excel-to-…
konradlang 897c8ee
Merge branch 'master' into 939-feature-convert-spreadsheets-excel-to-…
konradlang e704ffd
Merge branch 'master' into 939-feature-convert-spreadsheets-excel-to-…
konradlang ecfb2c7
refactor: implemented requested changes
ChrisiSailer 9a24168
refactor: added correct format
ChrisiSailer 771d682
Merge branch 'master' into 939-feature-convert-spreadsheets-excel-to-…
konradlang 6fb19fc
refactor: capitalized 'convert' in test names
ChrisiSailer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
171 changes: 171 additions & 0 deletions
171
backend/src/main/java/eu/bbmri_eric/negotiator/attachment/XlsxConverter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| package eu.bbmri_eric.negotiator.attachment; | ||
|
|
||
| import eu.bbmri_eric.negotiator.common.exceptions.PdfGenerationException; | ||
| import java.awt.Color; | ||
| import java.io.ByteArrayInputStream; | ||
| import java.io.ByteArrayOutputStream; | ||
| import java.io.IOException; | ||
| import lombok.extern.apachecommons.CommonsLog; | ||
| import org.apache.pdfbox.pdmodel.PDDocument; | ||
| import org.apache.pdfbox.pdmodel.PDPage; | ||
| import org.apache.pdfbox.pdmodel.PDPageContentStream; | ||
| import org.apache.pdfbox.pdmodel.common.PDRectangle; | ||
| import org.apache.pdfbox.pdmodel.font.PDType1Font; | ||
| import org.apache.pdfbox.pdmodel.font.Standard14Fonts; | ||
| 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.xssf.usermodel.XSSFWorkbook; | ||
|
|
||
| /** Converter for XLSX (Excel) files to PDF format. */ | ||
| @CommonsLog | ||
| class XlsxConverter implements FileTypeConverter { | ||
| /** Page margin in points. */ | ||
| private static final float MARGIN = 50; | ||
|
|
||
| /** Font size for cell text. */ | ||
| private static final float FONT_SIZE = 10; | ||
|
|
||
| /** Line leading (spacing between rows). */ | ||
| private static final float LEADING = 14; | ||
|
|
||
| /** Padding inside cells. */ | ||
| private static final float CELL_PADDING = 5; | ||
|
|
||
| /** Minimum width for columns. */ | ||
| private static final float MIN_COLUMN_WIDTH = 60; | ||
|
|
||
| @Override | ||
| public byte[] convertToPdf(final byte[] xlsxBytes) throws IOException, PdfGenerationException { | ||
| if (xlsxBytes == null || xlsxBytes.length == 0) { | ||
| throw new IllegalArgumentException("Input XLSX bytes are null or empty"); | ||
| } | ||
|
|
||
| log.debug("Converting XLSX to PDF, input size: " + xlsxBytes.length); | ||
|
ChrisiSailer marked this conversation as resolved.
|
||
|
|
||
| try (ByteArrayInputStream xlsxInputStream = new ByteArrayInputStream(xlsxBytes); | ||
| Workbook workbook = new XSSFWorkbook(xlsxInputStream); | ||
| PDDocument document = new PDDocument(); | ||
| ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream()) { | ||
|
|
||
| for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) { | ||
| Sheet sheet = workbook.getSheetAt(sheetIndex); | ||
| if (sheet.getPhysicalNumberOfRows() > 0) { | ||
| convertSheetToPdf(document, sheet); | ||
| } | ||
| } | ||
|
|
||
| if (document.getNumberOfPages() == 0) { | ||
| document.addPage(new PDPage(PDRectangle.A4)); | ||
| } | ||
|
|
||
| document.save(pdfOutputStream); | ||
| byte[] result = pdfOutputStream.toByteArray(); | ||
| log.debug("Successfully converted XLSX to PDF, output size: " + result.length); | ||
|
ChrisiSailer marked this conversation as resolved.
|
||
| return result; | ||
| } catch (Exception e) { | ||
| log.error("Error converting XLSX to PDF: " + e.getMessage(), e); | ||
|
ChrisiSailer marked this conversation as resolved.
|
||
| throw new PdfGenerationException(); | ||
| } | ||
| } | ||
|
|
||
| private void convertSheetToPdf(final PDDocument document, final Sheet sheet) throws IOException { | ||
| PDPage page = new PDPage(PDRectangle.A4); | ||
| document.addPage(page); | ||
|
|
||
| try (PDPageContentStream contentStream = | ||
| new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true)) { | ||
|
|
||
| float pageWidth = page.getMediaBox().getWidth() - (2 * MARGIN); | ||
| float yPosition = | ||
| drawSheetHeader(contentStream, sheet.getSheetName(), page.getMediaBox().getHeight()); | ||
|
|
||
| int maxCols = calculateMaxColumns(sheet); | ||
|
|
||
| float columnWidth = maxCols > 0 ? pageWidth / maxCols : MIN_COLUMN_WIDTH; | ||
| columnWidth = Math.max(columnWidth, MIN_COLUMN_WIDTH); | ||
|
|
||
| for (Row row : sheet) { | ||
| if (yPosition < MARGIN + LEADING) { | ||
| break; | ||
| } | ||
| drawRow(contentStream, row, yPosition, columnWidth, maxCols); | ||
| yPosition -= LEADING; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private float drawSheetHeader( | ||
| PDPageContentStream contentStream, String sheetName, float pageHeight) throws IOException { | ||
| float yPosition = pageHeight - MARGIN; | ||
| contentStream.beginText(); | ||
| contentStream.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD), FONT_SIZE + 2); | ||
| contentStream.newLineAtOffset(MARGIN, yPosition); | ||
| contentStream.showText("Sheet: " + sheetName); | ||
| contentStream.endText(); | ||
| return yPosition - (LEADING * 2); | ||
| } | ||
|
|
||
| private int calculateMaxColumns(Sheet sheet) { | ||
| int maxCols = 0; | ||
| for (Row row : sheet) { | ||
| if (row.getLastCellNum() > maxCols) { | ||
| maxCols = row.getLastCellNum(); | ||
| } | ||
| } | ||
| return maxCols; | ||
| } | ||
|
|
||
| private void drawRow( | ||
| PDPageContentStream contentStream, Row row, float yPosition, float columnWidth, int maxCols) | ||
| throws IOException { | ||
| float xPosition = MARGIN; | ||
| for (int cellIndex = 0; cellIndex < maxCols; cellIndex++) { | ||
| Cell cell = row.getCell(cellIndex); | ||
| drawCell(contentStream, cell, xPosition, yPosition, columnWidth); | ||
| xPosition += columnWidth; | ||
| } | ||
| } | ||
|
|
||
| private void drawCell(PDPageContentStream contentStream, Cell cell, float x, float y, float width) | ||
| throws IOException { | ||
| String cellValue = getCellValueAsString(cell); | ||
|
|
||
| contentStream.setStrokingColor(Color.LIGHT_GRAY); | ||
| contentStream.addRect(x, y - LEADING, width, LEADING); | ||
| contentStream.stroke(); | ||
|
|
||
| if (cellValue != null && !cellValue.isEmpty()) { | ||
| contentStream.beginText(); | ||
| contentStream.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), FONT_SIZE); | ||
| contentStream.newLineAtOffset(x + CELL_PADDING, y - FONT_SIZE); | ||
| String displayText = truncateText(cellValue, width - (2 * CELL_PADDING)); | ||
| contentStream.showText(displayText); | ||
| contentStream.endText(); | ||
| } | ||
| } | ||
|
|
||
| private String getCellValueAsString(final Cell cell) { | ||
| if (cell == null) { | ||
| return ""; | ||
| } | ||
|
|
||
| return switch (cell.getCellType()) { | ||
| case STRING -> cell.getStringCellValue(); | ||
| case NUMERIC -> String.valueOf(cell.getNumericCellValue()); | ||
| case BOOLEAN -> String.valueOf(cell.getBooleanCellValue()); | ||
| case FORMULA -> cell.getCellFormula(); | ||
| case BLANK -> ""; | ||
| default -> ""; | ||
| }; | ||
| } | ||
|
|
||
| private String truncateText(final String text, final float maxWidth) { | ||
| int maxChars = (int) (maxWidth / (FONT_SIZE * 0.6)); | ||
| if (text.length() > maxChars) { | ||
| return text.substring(0, Math.max(0, maxChars - 3)) + "..."; | ||
| } | ||
| return text; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I haven't noticed this piece of code last time. IMHO this switch is a code smell. Each converter should have the file types it supports:
boolean supports(String fileType)and the AttachmentConversionService would just do something like this:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Will not be changed in this PR - opened an new CR for this refactoring:
[FEATURE] Refatoring of attachment conversion services to provide supported file types.