updated code for html content for pdf
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
package net.gepafin.tendermanagement.util;
|
||||
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 = "<p>" + htmlContent + "</p>"; // Wrap in paragraph tags
|
||||
}
|
||||
|
||||
try {
|
||||
// Create a list to hold the elements parsed from the HTML
|
||||
List<Element> 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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user