712 lines
37 KiB
Java
712 lines
37 KiB
Java
package net.gepafin.tendermanagement.dao;
|
|
|
|
import com.fasterxml.jackson.databind.JsonNode;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import com.itextpdf.text.*;
|
|
import com.itextpdf.text.Element;
|
|
import com.itextpdf.text.Font;
|
|
import com.itextpdf.text.Image;
|
|
import com.itextpdf.text.Rectangle;
|
|
import com.itextpdf.text.pdf.*;
|
|
|
|
import jakarta.servlet.http.HttpServletRequest;
|
|
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
|
import net.gepafin.tendermanagement.entities.*;
|
|
import net.gepafin.tendermanagement.model.request.FieldLabelValuePairRequest;
|
|
import net.gepafin.tendermanagement.model.response.*;
|
|
import net.gepafin.tendermanagement.repositories.DocumentRepository;
|
|
import net.gepafin.tendermanagement.repositories.HubRepository;
|
|
import net.gepafin.tendermanagement.service.CallService;
|
|
import net.gepafin.tendermanagement.util.PdfUtils;
|
|
import net.gepafin.tendermanagement.util.Utils;
|
|
import net.gepafin.tendermanagement.util.Validator;
|
|
import org.apache.commons.lang3.StringUtils;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.stereotype.Component;
|
|
//import com.itextpdf.layout.element.
|
|
|
|
|
|
import java.io.ByteArrayOutputStream;
|
|
import java.io.IOException;
|
|
import java.text.NumberFormat;
|
|
import java.text.ParseException;
|
|
import java.util.*;
|
|
import java.util.List;
|
|
import java.util.stream.Collectors;
|
|
|
|
@Component
|
|
public class PdfDao {
|
|
|
|
@Value("${default.pdf.banner}")
|
|
private String defaultLogoUrl;
|
|
|
|
@Autowired
|
|
private CallService callService;
|
|
|
|
@Autowired
|
|
private ApplicationDao applicationDao;
|
|
|
|
@Autowired
|
|
private Validator validator;
|
|
|
|
@Autowired
|
|
private HubRepository hubRepository;
|
|
|
|
@Autowired
|
|
private DocumentRepository documentRepository;
|
|
|
|
public static final Logger log = LoggerFactory.getLogger(PdfDao.class);
|
|
|
|
public byte[] generatePdf(HttpServletRequest request,Long applicationId) {
|
|
try {
|
|
log.info("Start generating PDF for applicationId: {}", applicationId);
|
|
UserEntity userEntity = validator.validateUser(request);
|
|
ApplicationEntity applicationEntity = applicationDao.validateApplication(applicationId);
|
|
validator.validateUserWithCompany(request, applicationEntity.getCompanyId());
|
|
CallEntity call=callService.validateCall(applicationEntity.getCall().getId());
|
|
|
|
// Create a byte stream to hold the PDF
|
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
|
float leftMargin = 50f; // Adjust this for the left margin
|
|
|
|
Document document = new Document(PageSize.A4, leftMargin, 36f, 50f, 35);
|
|
PdfWriter writer = PdfWriter.getInstance(document, out);
|
|
// CustomPageEvent pageEvent = new CustomPageEvent(call.getName(), 0);
|
|
// writer.setPageEvent(pageEvent);
|
|
document.open();
|
|
String logoUrl=defaultLogoUrl;
|
|
|
|
Optional<HubEntity> hubEntity=hubRepository.findById(applicationEntity.getHubId());
|
|
if (Boolean.TRUE.equals(validator.isProductionProfileActivated()) && applicationEntity.getCall().getId().equals(23l)) {
|
|
logoUrl=defaultLogoUrl;
|
|
}
|
|
else if(hubEntity.isPresent()) {
|
|
if (hubEntity.get().getUniqueUuid().equals("p4lk3bcx1RStqTaIVVbXs")) {
|
|
logoUrl = hubEntity.get().getPdfBanner();
|
|
}
|
|
if (hubEntity.get().getUniqueUuid().equals("t7jh5wfg9QXylNaTZkPoE")) {
|
|
logoUrl = hubEntity.get().getPdfBanner();
|
|
}
|
|
|
|
}
|
|
// pageEvent.setTotalPages(writer.getPageNumber());
|
|
// addLogo(document, "logo.jpg"); // Add your image path here the migration code after cherry-pick
|
|
addLogo(document, logoUrl,applicationEntity);
|
|
|
|
|
|
BaseColor customColor = new BaseColor(0, 128, 0); // Adjust RGB values as needed
|
|
// Define fonts and styles
|
|
BaseColor greenColor = new BaseColor(0, 128, 0); // Adjust RGB values as needed
|
|
BaseColor darkGreenColor = new BaseColor(1, 50, 32); // Adjust RGB values as needed
|
|
Font titleFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 16, customColor);
|
|
Font sectionFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12,darkGreenColor);
|
|
Font labelFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12,new BaseColor(113,121,126)); // Light grey);
|
|
Font smallFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8,new BaseColor(105, 105, 105));
|
|
Font valueFont=FontFactory.getFont(FontFactory.HELVETICA_BOLD,10,new BaseColor(178, 190, 181));
|
|
Paragraph title = new Paragraph(call.getName(), titleFont);
|
|
title.setAlignment(Element.ALIGN_LEFT);
|
|
document.add(title);
|
|
|
|
BaseColor greyColor=new BaseColor(178, 190, 181); // Very light grey color
|
|
addColoredLines(writer,document,greyColor);
|
|
document.add(new Paragraph(" "));
|
|
|
|
ApplicationGetResponseBean applicationGetResponseBean=applicationDao.getApplicationByFormId(request, applicationId, null);
|
|
for(FormApplicationResponse formApplicationResponse: applicationGetResponseBean.getForm()) {
|
|
List<FieldLabelValuePairRequest> fieldLabelValuePairRequests = getFormFieldsToLabels(formApplicationResponse,writer,document,applicationEntity);
|
|
addColoredLines(writer,document,greenColor);
|
|
document.add(new Paragraph(" ")); // Add line break
|
|
}
|
|
document.add(new Paragraph("\n")); // Add line break
|
|
|
|
|
|
document.close();
|
|
|
|
// Convert to byte array for response
|
|
byte[] pdfBytes =PdfPageNumberInserter.addPageNumbers(out.toByteArray());
|
|
|
|
return pdfBytes;
|
|
} catch (Exception e) {
|
|
log.error("Error generating PDF for applicationId: {}", applicationId, e);
|
|
e.printStackTrace();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private void addLabelValuePair(PdfWriter writer,Document document, String label, Object value, Font labelFont,Font valueFont,ContentResponseBean contentResponseBean, ApplicationEntity applicationEntity) throws DocumentException {
|
|
// Add label
|
|
Map<String, Boolean> stateFieldMap= new HashMap<>();
|
|
if (Boolean.TRUE.equals(validator.isProductionProfileActivated()) && applicationEntity.getCall().getId().equals(23l)) {
|
|
for (SettingResponseBean settingResponseBean : contentResponseBean.getSettings()) {
|
|
if (settingResponseBean.getName().equals("isRequestedAmount") && settingResponseBean.getValue().equals(Boolean.TRUE)) {
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
Paragraph labelParagraph = new Paragraph(label, labelFont);
|
|
labelParagraph.setSpacingAfter(-10f);
|
|
document.add(labelParagraph);
|
|
float leftMargin = 20f;
|
|
PdfContentByte canvas = writer.getDirectContent();
|
|
|
|
// Setting the color and width of the line
|
|
float lineWidth = 1.0f; // Thickness of the line
|
|
canvas.setLineWidth(lineWidth);
|
|
|
|
// Get the current vertical position in the document
|
|
float yPos = writer.getVerticalPosition(true) - 10f; // Adjust this to move line slightly below current content
|
|
|
|
// Define start and end points for the line (relative to the page size and margins)
|
|
|
|
// if (yPos <= 140) {
|
|
// // If xEnd is less than or equal to 200, generate a new page
|
|
// document.newPage();
|
|
// } // Add a gap between the label and value
|
|
document.add(new Paragraph(" ")); // Adding an empty paragraph for spacing
|
|
// Create value cell with rounded corners
|
|
PdfPTable valueTable = new PdfPTable(1);
|
|
valueTable.setWidthPercentage(100);
|
|
|
|
|
|
Object finalValue = value;
|
|
List<Object> criteriaObject = (List<Object>) contentResponseBean.getSettings().stream()
|
|
.filter(setting -> GepafinConstant.CRITERIA_TABLE_COLUMNS.equals(setting.getName()))
|
|
.findFirst()
|
|
.map(setting -> {
|
|
try {
|
|
// Assuming setting.getValue() contains the JSON string or object
|
|
return PdfUtils.extractRows(finalValue);
|
|
} catch (Exception e) {
|
|
throw new RuntimeException("Error extracting rows from setting value", e);
|
|
}
|
|
})
|
|
.orElse(null);
|
|
|
|
|
|
// Update value if criteriaObject is not null
|
|
if (criteriaObject != null) {
|
|
value = criteriaObject;
|
|
}
|
|
|
|
|
|
// Update value if criteriaObject is not null
|
|
|
|
if (value instanceof List<?>) {
|
|
// Further check if the list contains Strings
|
|
List<?> list = (List<?>) value;
|
|
if (!list.isEmpty() && list.get(0) instanceof String) {
|
|
// Cast to List<String>
|
|
List<String> values = (List<String>) value;
|
|
|
|
// Loop through the list of strings and create a cell for each string
|
|
for (String item : values) {
|
|
|
|
// PdfPCell valueCell = new PdfPCell(new Phrase(item, valueFont));
|
|
PdfPCell valueCell = PdfUtils.htmlToPdfPCell(item, valueFont);
|
|
valueCell.setPaddingLeft(10f); // Adjust left padding as needed
|
|
valueCell.setPaddingTop(0f); // Remove padding from top to allow vertical centering
|
|
valueCell.setPaddingBottom(6f);
|
|
valueCell.setMinimumHeight(30f); // Set a fixed height for the cell
|
|
valueCell.setPaddingLeft(leftMargin); // Increase left margin for value
|
|
valueCell.setBorder(Rectangle.NO_BORDER); // Remove border for value cell
|
|
valueCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
|
valueCell.setHorizontalAlignment(Element.ALIGN_LEFT);
|
|
valueCell.setCellEvent(new RoundedCorners()); // Apply rounded corners
|
|
valueTable.setSpacingAfter(-15f);
|
|
|
|
// Add the cell to the table
|
|
valueTable.addCell(valueCell);
|
|
}
|
|
|
|
// Finally, add the table to the document
|
|
document.add(valueTable);
|
|
}
|
|
else if (!list.isEmpty() && list.get(0) instanceof Map<?, ?>) {
|
|
Object object = value;
|
|
String stringvalue = Utils.convertToString(object);
|
|
List<Map<String, Object>> fieldValueList = Utils.convertJsonStringIntoJsonList(stringvalue);
|
|
document = createPdfTable(fieldValueList, document, contentResponseBean);
|
|
}
|
|
}
|
|
else {
|
|
|
|
String fieldValue=Utils.convertToString(value);
|
|
Image img = null; // This may throw MalformedURLException
|
|
if (fieldValue.trim().equalsIgnoreCase("true")) {
|
|
// Use images for tick and cross
|
|
try {
|
|
DocumentEntity documentEntity = documentRepository.findBySource(GepafinConstant.PDF_TRUE).get(0);
|
|
|
|
// img = Image.getInstance("true.jpg"); update code after cherry-pick
|
|
img = Image.getInstance(documentEntity.getFilePath());
|
|
} catch (IOException e) {
|
|
log.error("Error while uploading image for pdf for true");
|
|
}
|
|
img.scaleAbsolute(15, 15); // Resize the image if needed
|
|
|
|
PdfPCell cell = new PdfPCell(img);
|
|
cell.setPadding(0); // Remove padding
|
|
cell.setBorder(Rectangle.NO_BORDER); // Remove border
|
|
cell.setMinimumHeight(15f); // Set height to fit checkbox image
|
|
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
|
cell.setHorizontalAlignment(Element.ALIGN_LEFT); // Align the checkbox image to the left
|
|
|
|
valueTable.addCell(cell); // Add cell with checkbox to the table
|
|
document.add(valueTable);
|
|
} else if (fieldValue.trim().equalsIgnoreCase("false")) {
|
|
// Use images for tick and cross
|
|
try {
|
|
DocumentEntity documentEntity = documentRepository.findBySource(GepafinConstant.PDF_FALSE).get(0);
|
|
|
|
img = Image.getInstance(documentEntity.getFilePath());
|
|
} catch (IOException e) {
|
|
log.error("Error while uploading image for pdf for false");
|
|
}
|
|
img.scaleAbsolute(15, 15); // Resize the image if needed
|
|
|
|
PdfPCell cell = new PdfPCell(img);
|
|
cell.setPadding(0); // Remove padding
|
|
cell.setBorder(Rectangle.NO_BORDER); // Remove border
|
|
cell.setMinimumHeight(15f); // Set height to fit checkbox image
|
|
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
|
cell.setHorizontalAlignment(Element.ALIGN_LEFT); // Align the checkbox image to the left
|
|
|
|
valueTable.addCell(cell); // Add cell with checkbox to the table
|
|
document.add(valueTable);
|
|
}
|
|
else {
|
|
|
|
if (value instanceof String) {
|
|
String fieldValue1 = (String) value;
|
|
if (Utils.isValidDateString(fieldValue1)) {
|
|
fieldValue1 = Utils.formatDateString(String.valueOf(value));
|
|
}
|
|
if(contentResponseBean.getName().equals("numberinput") && Boolean.TRUE.equals(Utils.isNumeric(fieldValue))){
|
|
fieldValue1=Utils.convertToItalianFormat(fieldValue);
|
|
}
|
|
// PdfPCell valueCell = new PdfPCell(new Phrase(fieldValue1, valueFont));
|
|
PdfPCell valueCell = PdfUtils.htmlToPdfPCell(fieldValue1, valueFont);
|
|
valueCell.setMinimumHeight(30f); // Set a fixed height for the cell
|
|
valueCell.setPaddingLeft(10f); // Adjust left padding as needed
|
|
valueCell.setPaddingTop(0f); // Remove padding from top to allow vertical centering
|
|
valueCell.setPaddingBottom(6f);
|
|
valueCell.setPaddingLeft(leftMargin); // Increase left margin for value
|
|
valueCell.setBorder(Rectangle.NO_BORDER); // Remove border for value cell
|
|
valueCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
|
valueCell.setHorizontalAlignment(Element.ALIGN_LEFT);
|
|
valueCell.setCellEvent(new RoundedCorners()); // Apply rounded corners
|
|
valueTable.addCell(valueCell);
|
|
valueTable.setSpacingAfter(-15f);
|
|
document.add(valueTable);
|
|
}
|
|
}
|
|
|
|
}
|
|
document.add(new Paragraph("\n")); // Add line break after each value
|
|
}
|
|
|
|
private Document createPdfTable(List<Map<String, Object>> extractedData, Document document, ContentResponseBean contentResponseBean) throws DocumentException {
|
|
// Create a PdfPTable with dynamic column count based on stateFieldMap size
|
|
Map<String, String> stateFieldMap = new LinkedHashMap<>();
|
|
Map<String, Boolean> stateFieldBoolean = new LinkedHashMap<>();
|
|
Map<String, Boolean> formulaEnabledMap = new LinkedHashMap<>();
|
|
Map<String, String> formulaTypeMap = new LinkedHashMap<>();
|
|
Map<String, String> fieldTypeMap = new LinkedHashMap<>();
|
|
Map<String, String> totalMap = new LinkedHashMap<>();
|
|
Font lightGrayFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new BaseColor(110, 110, 110)); // Light gray
|
|
|
|
|
|
contentResponseBean.getSettings().stream()
|
|
.filter(setting -> "table_columns".equals(setting.getName()) || "criteria_table_columns".equals(setting.getName())) // Check for "table_columns"
|
|
.map(SettingResponseBean::getValue)
|
|
.filter(Objects::nonNull) // Ensure value is not null
|
|
.filter(settingValue -> settingValue instanceof Map) // Ensure value is a Map
|
|
.map(settingValue -> (Map<String, Object>) settingValue) // Cast to Map
|
|
.map(valueMap -> (List<Map<String, Object>>) valueMap.get("stateFieldData")) // Extract stateFieldData list
|
|
.filter(Objects::nonNull) // Ensure stateFieldData is not null
|
|
.flatMap(List::stream) // Flatten the list of field data maps
|
|
.forEach(fieldData -> {
|
|
String fieldName = (String) fieldData.get("name"); // Get the name field
|
|
String fieldDataValue = (String) fieldData.get("label"); // Get the predefined field
|
|
Boolean predefined = (Boolean) fieldData.get("predefined"); // Get the predefined field
|
|
Boolean isFormulaEnabled = (Boolean) fieldData.get("enableFormula");
|
|
String formulaType = (String) fieldData.get("lastRowFormula");
|
|
String fieldType = (String) fieldData.get("fieldtype"); // Get the field type (e.g., numeric)
|
|
String total= (String) fieldData.get("lastRowText");
|
|
if (fieldName != null && fieldDataValue != null) {
|
|
stateFieldMap.put(fieldName, fieldDataValue);
|
|
}
|
|
if (fieldName != null && predefined != null) {
|
|
stateFieldBoolean.put(fieldName, predefined);
|
|
}
|
|
formulaEnabledMap.put(fieldName, isFormulaEnabled != null && isFormulaEnabled);
|
|
if (formulaType != null) {
|
|
formulaTypeMap.put(fieldName, formulaType);
|
|
}
|
|
if (fieldType != null) {
|
|
fieldTypeMap.put(fieldName, fieldType); // Store the fieldType in the map
|
|
}
|
|
if(total!=null){
|
|
totalMap.put(fieldName,total);
|
|
}
|
|
});
|
|
|
|
PdfPTable table = new PdfPTable(stateFieldMap.size()); // Number of columns equals the number of map entries
|
|
table.setWidthPercentage(100); // Set table width to 100%
|
|
table.setTableEvent(new RoundedBorderEvent());
|
|
|
|
Font textFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new BaseColor(105, 105, 105)); // Gray text
|
|
float rowHeight = 20f; // Example row height
|
|
float maxTableHeight = 700f; // Maximum height of the table before a page break
|
|
boolean headersAdded = false; // Flag to check if headers have been added
|
|
|
|
List<String> trueKeys = new ArrayList<>();
|
|
List<String> falseKeys = new ArrayList<>();
|
|
for (Map.Entry<String, Boolean> entry : stateFieldBoolean.entrySet()) {
|
|
if (Boolean.TRUE.equals(entry.getValue())) {
|
|
trueKeys.add(entry.getKey()); // Store true keys
|
|
} else {
|
|
falseKeys.add(entry.getKey()); // Store false keys
|
|
}
|
|
}
|
|
List<String> orderedKeys = new ArrayList<>(trueKeys);
|
|
orderedKeys.addAll(falseKeys);
|
|
if (!headersAdded) {
|
|
for (String key : orderedKeys) {
|
|
String headerValue = stateFieldMap.get(key); // Header text
|
|
PdfPCell headerCell = PdfUtils.htmlToPdfPCell(headerValue, textFont);
|
|
headerCell.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
|
|
headerCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
|
headerCell.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
|
|
headerCell.setMinimumHeight(30f); // Set a fixed height for the cell
|
|
headerCell.setPaddingLeft(10f); // Adjust left padding as needed
|
|
headerCell.setPaddingTop(0f); // Remove padding from top to allow vertical centering
|
|
headerCell.setPaddingBottom(6f);
|
|
table.addCell(headerCell); // Add the header cell to the table
|
|
}
|
|
headersAdded = true; // Prevent headers from being added again
|
|
}
|
|
Map<String, Double> columnSums = new HashMap<>();
|
|
|
|
for (Map<String, Object> row : extractedData) {
|
|
for (String key : orderedKeys) {
|
|
if (stateFieldMap.containsKey(key)) { // Only add data cell if key is in stateFieldMap
|
|
Object value = row.getOrDefault(key, ""); // Fetch value or use empty string if key not present
|
|
// String fieldValue= (String) value;
|
|
String fieldValue = value != null ? value.toString() : "";
|
|
// if(Boolean.TRUE.equals(Utils.isItalianFormattedAmount(fieldValue)) ){
|
|
//// fieldValue= String.valueOf(Utils.convertToItalianFormat(fieldValue));
|
|
// }
|
|
if (Boolean.TRUE.equals(formulaEnabledMap.get(key)) && Boolean.TRUE.equals(GepafinConstant.NUMERIC.equalsIgnoreCase(fieldTypeMap.get(key)))) {
|
|
calculateValue(key, fieldValue, formulaTypeMap, columnSums);
|
|
}
|
|
String fieldLabel = stateFieldMap.getOrDefault(key, "");
|
|
|
|
if(Boolean.FALSE.equals(fieldLabel.equalsIgnoreCase("Anno")) && Boolean.TRUE.equals(GepafinConstant.NUMERIC.equalsIgnoreCase(fieldTypeMap.get(key)))) {
|
|
if (Boolean.TRUE.equals(Utils.isNumeric(fieldValue))) {
|
|
fieldValue = Utils.convertToItalianFormat(fieldValue);
|
|
}
|
|
}
|
|
PdfPCell dataCell = PdfUtils.htmlToPdfPCell(fieldValue != null ? fieldValue : "", textFont);
|
|
dataCell.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for the cell
|
|
dataCell.setMinimumHeight(30f);
|
|
dataCell.setPaddingLeft(10f); // Adjust left padding as needed
|
|
dataCell.setPaddingTop(0f); // Remove padding from top to allow vertical centering
|
|
dataCell.setPaddingBottom(6f);
|
|
dataCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
|
dataCell.setHorizontalAlignment(Element.ALIGN_LEFT);
|
|
table.addCell(dataCell); // Add the cell to the table
|
|
}
|
|
}
|
|
|
|
if (table.getTotalHeight() + rowHeight > maxTableHeight) {
|
|
document.add(table); // Add the table to the document
|
|
document.newPage(); // Start a new page
|
|
table = new PdfPTable(stateFieldMap.size()); // Create a new table for the new page
|
|
table.setWidthPercentage(100); // Reset table width
|
|
headersAdded = false; // Reset the header flag for the new page
|
|
}
|
|
}
|
|
|
|
|
|
for (String key : orderedKeys) {
|
|
if (Boolean.TRUE.equals(formulaEnabledMap.get(key)) &&
|
|
(GepafinConstant.SUM.equalsIgnoreCase(formulaTypeMap.get(key)) ||
|
|
GepafinConstant.MULTIPLY.equalsIgnoreCase(formulaTypeMap.get(key)))) {
|
|
|
|
if (columnSums.containsKey(key)) {
|
|
double total = columnSums.getOrDefault(key, 0.0); // Get the total for the column
|
|
// PdfPCell sumCell = PdfUtils.htmlToPdfPCell(Utils.convertToItalianFormat(String.valueOf(total)), textFont);
|
|
// Convert total to Italian format, defaulting to "0" if null
|
|
String formattedTotal = Utils.convertToItalianFormat(String.valueOf(total));
|
|
|
|
// Create a table cell with the formatted value
|
|
PdfPCell sumCell = new PdfPCell(new Phrase(formattedTotal,lightGrayFont));
|
|
|
|
|
|
sumCell.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for totals
|
|
sumCell.setHorizontalAlignment(Element.ALIGN_CENTER);
|
|
sumCell.setPaddingTop(8f);
|
|
sumCell.setMinimumHeight(30f);
|
|
table.addCell(sumCell); // Add total for the column
|
|
} else {
|
|
PdfPCell emptyCell = new PdfPCell(new Phrase(""));
|
|
emptyCell.setBackgroundColor(new BaseColor(239, 243, 248));
|
|
table.addCell(emptyCell);
|
|
}
|
|
} else {
|
|
String total=null;
|
|
if (totalMap.containsKey(key)) {
|
|
total=totalMap.getOrDefault(key, "");
|
|
}
|
|
PdfPCell emptyCell = new PdfPCell(new Phrase(total,lightGrayFont));
|
|
emptyCell.setPaddingTop(8f);
|
|
emptyCell.setPaddingLeft(8f);
|
|
emptyCell.setBackgroundColor(new BaseColor(239, 243, 248));
|
|
table.addCell(emptyCell);
|
|
}
|
|
|
|
}
|
|
|
|
// Add the last table to the document
|
|
document.add(table);
|
|
|
|
return document;
|
|
}
|
|
|
|
private static void calculateValue(String key, String fieldValue, Map<String, String> formulaTypeMap, Map<String, Double> columnSums) {
|
|
try {
|
|
if (Boolean.FALSE.equals(StringUtils.isEmpty(fieldValue))) {
|
|
// Use Locale.ITALY to parse the number with the Italian format (comma as decimal separator)
|
|
NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH);
|
|
Number number = format.parse(fieldValue); // Parse the fieldValue as a number
|
|
double numericValue = number.doubleValue(); // Convert the parsed number to double
|
|
|
|
if (GepafinConstant.SUM.equalsIgnoreCase(formulaTypeMap.get(key))) {
|
|
columnSums.merge(key, numericValue, Double::sum);
|
|
} else if (GepafinConstant.MULTIPLY.equalsIgnoreCase(formulaTypeMap.get(key))) {
|
|
columnSums.merge(key, numericValue, (existing, newValue) -> existing == null ? newValue : existing * newValue);
|
|
}
|
|
}
|
|
} catch (ParseException e) {
|
|
}
|
|
}
|
|
|
|
public static class RoundedBorderEvent implements PdfPTableEvent {
|
|
@Override
|
|
public void tableLayout(PdfPTable table, float[][] widths, float[] heights,
|
|
int headerRows, int rowStart, PdfContentByte[] canvases) {
|
|
PdfContentByte canvas = canvases[PdfPTable.BASECANVAS];
|
|
|
|
// Get the table boundaries
|
|
float left = widths[0][0];
|
|
float right = widths[0][widths[0].length - 1];
|
|
float top = heights[0];
|
|
float bottom = heights[heights.length - 1];
|
|
|
|
// Define the corner radius
|
|
float radius = 20f;
|
|
|
|
// Draw a rounded rectangle around the table
|
|
canvas.roundRectangle(left, bottom, right - left, top - bottom, radius);
|
|
canvas.stroke();
|
|
}
|
|
}
|
|
public List<FieldLabelValuePairRequest> getFormFieldsToLabels(FormApplicationResponse responseBean,PdfWriter writer,Document document,ApplicationEntity applicationEntity) {
|
|
List<FieldLabelValuePairRequest> labelValuePairs = new ArrayList<>();
|
|
|
|
Font labelFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12,new BaseColor(113,121,126)); // Light grey);
|
|
Font valueFont=FontFactory.getFont(FontFactory.HELVETICA_BOLD,10,new BaseColor(178, 190, 181));
|
|
|
|
|
|
// Get form fields and contents from the response
|
|
List<ApplicationFormFieldResponseBean> formFields = responseBean.getFormFields();
|
|
List<ContentResponseBean> contents = responseBean.getContent();
|
|
|
|
// Iterate through each content in the response
|
|
for (ContentResponseBean content : contents) {
|
|
String contentId = content.getId(); // Content ID
|
|
String label = content.getLabel(); // Content label
|
|
String name = content.getName(); // Content name
|
|
Object fieldValue = "";
|
|
|
|
String contentLabel = content.getSettings().stream()
|
|
.filter(setting -> "label".equals(setting.getName())) // Filter settings by name
|
|
.map(SettingResponseBean::getValue) // Extract the value from the matching setting
|
|
.map(Object::toString) // Convert the value to a string
|
|
.findFirst() // Get the first matching value
|
|
.orElse(null); // If no match is found, set label to null
|
|
// Find the form field in the response that matches the contentId
|
|
if (name.equals("paragraph")){
|
|
// String paragraph = content.getSettings().stream()
|
|
// .filter(setting -> "text".equals(setting.getName())) // Filter settings by name
|
|
// .map(SettingResponseBean::getValue) // Extract the value from the matching setting
|
|
// .map(Object::toString) // Convert the value to a string
|
|
// .findFirst() // Get the first matching value
|
|
// .orElse(null);
|
|
String paragraph = content.getSettings().stream()
|
|
.filter(setting -> "text".equals(setting.getName())) // Filter settings by name
|
|
.map(SettingResponseBean::getValue) // Extract the value from the matching setting
|
|
.map(value -> value != null ? value.toString() : " ") // Replace null with an empty string
|
|
.findFirst() // Get the first matching value
|
|
.orElse(null); // Return null if no value is found
|
|
|
|
Paragraph labelParagraph = new Paragraph();
|
|
PdfPCell labelCell = new PdfPCell(PdfUtils.htmlToPdfPCell(paragraph,labelFont));
|
|
labelCell.setBorder(Rectangle.NO_BORDER);
|
|
labelCell.setGrayFill(7);
|
|
labelCell.setPadding(5);
|
|
labelCell.setNoWrap(false); // wrap long text
|
|
labelCell.setUseAscender(true);
|
|
labelCell.setUseDescender(true); // allow text wrapping
|
|
|
|
|
|
// Create a PdfPTable with 1 column and add the PdfPCell to it
|
|
PdfPTable table = new PdfPTable(1);
|
|
table.setWidthPercentage(100);
|
|
table.addCell(labelCell);
|
|
table.setSplitLate(false);
|
|
table.setSplitRows(true);
|
|
table.setKeepTogether(false);
|
|
labelCell.setMinimumHeight(0);
|
|
|
|
labelParagraph.add(table);
|
|
try {
|
|
document.add(labelParagraph);
|
|
document.add(new Paragraph(" "));
|
|
|
|
} catch (DocumentException e) {
|
|
throw new RuntimeException(e);
|
|
}
|
|
}
|
|
Optional<ApplicationFormFieldResponseBean> matchingFormField = formFields.stream()
|
|
.filter(formField -> formField.getFieldId().equals(contentId))
|
|
.findFirst();
|
|
|
|
// If a matching form field is found, process its value
|
|
if (matchingFormField.isPresent()) {
|
|
ApplicationFormFieldResponseBean formField = matchingFormField.get();
|
|
fieldValue = formField.getFieldValue();
|
|
|
|
// If fieldValue is null, set it to an empty string
|
|
if (fieldValue == null) {
|
|
fieldValue = "";
|
|
}
|
|
|
|
// Process 'fileupload' and 'checkboxes' cases as in the original logic
|
|
if (name.equals("fileupload") || name.equals("fileselect")) {
|
|
if (fieldValue instanceof List<?> && ((List<?>) fieldValue).stream().allMatch(item -> item instanceof DocumentResponseBean)) {
|
|
List<DocumentResponseBean> documentList = (List<DocumentResponseBean>) fieldValue;
|
|
List<String> names = documentList.stream()
|
|
.map(DocumentResponseBean::getName)
|
|
.collect(Collectors.toList());
|
|
fieldValue = names;
|
|
}
|
|
} else if (name.equals("checkboxes") && fieldValue instanceof List<?>) {
|
|
List<String> check = (List<String>) fieldValue;
|
|
List<SettingResponseBean> settingResponseBeans = content.getSettings();
|
|
List<String> matchedLabels = new ArrayList<>();
|
|
|
|
for (SettingResponseBean settingResponseBean : settingResponseBeans) {
|
|
if (settingResponseBean.getValue() instanceof List<?>) {
|
|
List<Map<String, String>> options = (List<Map<String, String>>) settingResponseBean.getValue();
|
|
|
|
for (Map<String, String> field : options) {
|
|
for (String val : check) {
|
|
String name1 = field.get("name");
|
|
if (val.equals(name1)) {
|
|
String labelVal = field.get("label");
|
|
if (labelVal != null) {
|
|
matchedLabels.add(labelVal);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
fieldValue = matchedLabels;
|
|
}
|
|
|
|
// Further processing of field value (e.g., finding labels in options)
|
|
fieldValue = findLabelInOptions(content.getSettings(), fieldValue);
|
|
}
|
|
try {
|
|
if((contentLabel==null || StringUtils.isEmpty(contentLabel)) && (fieldValue==null || StringUtils.isEmpty(fieldValue.toString()))) {
|
|
continue;
|
|
}
|
|
addLabelValuePair(writer, document, contentLabel, fieldValue, labelFont, valueFont, content,applicationEntity);
|
|
} catch (DocumentException e) {
|
|
log.error("Error checking object: " + e.getMessage(), e);
|
|
|
|
}
|
|
// } labelValuePairs.add(new FieldLabelValuePairRequest(contentLabel, fieldValue));
|
|
}
|
|
|
|
return labelValuePairs;
|
|
}
|
|
|
|
|
|
public static Object findLabelInOptions(List<SettingResponseBean> settings, Object valueToFind) {
|
|
ObjectMapper objectMapper = new ObjectMapper();
|
|
|
|
try {
|
|
if (valueToFind instanceof String) {
|
|
String searchValue = (String) valueToFind;
|
|
for (SettingResponseBean setting : settings) {
|
|
Object value = setting.getValue();
|
|
if (value instanceof List) {
|
|
List<?> options = (List<?>) value;
|
|
for (Object option : options) {
|
|
JsonNode optionNode = objectMapper.convertValue(option, JsonNode.class);
|
|
if (optionNode.get("name").asText().equals(searchValue)) {
|
|
return optionNode.get("label").asText();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} catch (Exception e) {
|
|
}
|
|
return valueToFind;
|
|
}
|
|
|
|
public void addLogo(Document document, String logoPath,ApplicationEntity applicationEntity) throws Exception {
|
|
Image logo = Image.getInstance(logoPath);
|
|
if (Boolean.TRUE.equals(validator.isProductionProfileActivated()) && applicationEntity.getCall().getId().equals(23l)) {
|
|
logo.scaleToFit(120, 60);
|
|
}
|
|
else {
|
|
logo.scaleToFit(document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(), // Fit to document width
|
|
document.getPageSize().getHeight() / 4); // Adjust the height as needed (1/4th of the page height)
|
|
}
|
|
logo.setAlignment(Image.ALIGN_CENTER); // Align logo to center
|
|
document.add(logo);
|
|
|
|
// Add some space after logo
|
|
document.add(new Paragraph("\n")); // Adding space after the logo
|
|
}
|
|
public void addColoredLines(PdfWriter writer, Document document, BaseColor color){
|
|
PdfContentByte canvas = writer.getDirectContent();
|
|
|
|
// Setting the color and width of the line
|
|
canvas.setColorStroke(color);
|
|
float lineWidth = 1.0f; // Thickness of the line
|
|
canvas.setLineWidth(lineWidth);
|
|
|
|
// Get the current vertical position in the document
|
|
float yPos = writer.getVerticalPosition(true) - 10f; // Adjust this to move line slightly below current content
|
|
|
|
// Define start and end points for the line (relative to the page size and margins)
|
|
float xStart = document.leftMargin(); // Start from the left margin
|
|
float xEnd = document.getPageSize().getWidth() - document.rightMargin(); // End at the right margin
|
|
|
|
// Draw the line at the current Y position
|
|
canvas.moveTo(xStart, yPos); // Move to the starting point
|
|
canvas.lineTo(xEnd, yPos); // Draw the line to the end point
|
|
canvas.stroke(); // Apply the stroke (line)
|
|
}
|
|
}
|