package net.gepafin.tendermanagement.util; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.html.simpleparser.HTMLWorker; import com.itextpdf.text.html.simpleparser.StyleSheet; import com.itextpdf.text.Paragraph; import java.io.StringReader; import java.util.List; import org.springframework.stereotype.Component; @Component public class PdfUtils { public static PdfPCell htmlToPdfPCell(String htmlContent, Font font) { PdfPCell cell = new PdfPCell(); // Check if the content is not null or empty if (htmlContent != null && !htmlContent.trim().isEmpty()) { // Wrap plain text in a paragraph tag if it doesn't contain any HTML // Check if the string does not contain any '<' or '>' characters if (!htmlContent.contains("<") || !htmlContent.contains(">")) { htmlContent = "

" + htmlContent + "

"; // Wrap in paragraph tags } try { // Create a list to hold the elements parsed from the HTML List elements = HTMLWorker.parseToList(new StringReader(htmlContent), new StyleSheet()); // Create a paragraph to hold the formatted text Paragraph paragraph = new Paragraph(); // Add each element to the paragraph for (Element element : elements) { // If the element is a Paragraph, set the font directly if (element instanceof Paragraph) { ((Paragraph) element).setFont(font); } // If the element is a Chunk, set the font directly else if (element instanceof com.itextpdf.text.Chunk) { ((com.itextpdf.text.Chunk) element).setFont(font); } // Add the element to the paragraph paragraph.add(element); } // Add the paragraph to the cell cell.addElement(paragraph); } catch (Exception e) { e.printStackTrace(); // Log the exception for debugging } } return cell; } public static Object extractRows(Object content) throws Exception { ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode; // Check if input is already a JSON tree (Object) or a String if (content instanceof String) { rootNode = objectMapper.readTree((String) content); } else { rootNode = objectMapper.valueToTree(content); } // Extract "rows" dynamically JsonNode rowsArray = rootNode.get("rows"); // Convert to a generic List return objectMapper.convertValue(rowsArray, List.class); } }