Implemented export to PDF test

This commit is contained in:
Francesco Mangiacrapa 2023-09-18 17:03:12 +02:00
parent 5a9cb2452a
commit 947f390708
4 changed files with 660 additions and 5 deletions

12
pom.xml
View File

@ -5,7 +5,7 @@
<parent>
<artifactId>maven-parent</artifactId>
<groupId>org.gcube.tools</groupId>
<version>1.1.0</version>
<version>1.2.0</version>
</parent>
<groupId>org.gcube.application</groupId>
@ -102,7 +102,7 @@
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.liferay.portal</groupId>
<artifactId>portal-service</artifactId>
@ -110,6 +110,14 @@
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itext7-core -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>8.0.1</version>
<type>pom</type>
</dependency>
<!-- LOGGER -->
<dependency>
<groupId>org.slf4j</groupId>

View File

@ -42,6 +42,37 @@ public class URLParserUtil {
return queryParameter;
}
/**
* Sets the value of parameter.
*
* @param wmsParam the wms param
* @param wmsLink the wms link
* @param newValue the new value
* @param addIfNotExists the add if not exists
* @return the string
*/
public static String setValueOfParameter(String wmsParam, String wmsLink, String newValue, boolean addIfNotExists) {
String toLowerWmsLink = wmsLink.toLowerCase();
String toLowerWmsParam = wmsParam.toLowerCase();
int index = toLowerWmsLink.indexOf(toLowerWmsParam + "="); // END WITH CHAR "=" TO BE SURE THAT IT IS A
// PARAMETER
if (index > -1) {
int indexStartValue = index + toLowerWmsParam.length() + 1; // add +1 for char '='
int indexOfSeparator = toLowerWmsLink.indexOf("&", indexStartValue); // GET THE FIRST "&" STARTING FROM
// INDEX VALUE
// logger.trace("indexOfSeparator index of "+wmsParam+ " is: "+indexOfSeparator);
int indexEndValue = indexOfSeparator != -1 ? indexOfSeparator : toLowerWmsLink.length();
// logger.trace("end: "+indexEndValue);
return wmsLink.substring(0, indexStartValue) + newValue
+ wmsLink.substring(indexEndValue, wmsLink.length());
} else if (addIfNotExists) {
wmsLink += "&" + wmsParam + "=" + newValue;
}
// logger.trace("return value: "+value);
return wmsLink;
}
/**
* Extract value of parameter from URL.

View File

@ -41,7 +41,7 @@ public class Geoportal_DataMapper_Tests {
//private static String PROFILE_ID = "concessioni-estere";
private static String PROFILE_ID = "profiledConcessioni";
private static String PROJECT_ID = "6475a6a2a827c6201915917d"; //63d011c4dcac4551b9a6b930 //6442653ac6a0422d9e9042e0 //6399de3ca0a4545420373251
private static String PROJECT_ID = "6384d44d308f5c28c5ee0a01"; //63d011c4dcac4551b9a6b930 //6442653ac6a0422d9e9042e0 //6399de3ca0a4545420373251
//IMPORTANT!!!! #NB SET USERNAME = null to test PUBLIC ACCESS
@ -75,7 +75,7 @@ public class Geoportal_DataMapper_Tests {
*
* @return the client
*/
//@Before
@Before
public void getClient() {
readContextSettings();
// assumeTrue(GCubeTest.isTestInfrastructureEnabled());
@ -113,7 +113,7 @@ public class Geoportal_DataMapper_Tests {
/**
* Test read project view.
*/
//@Test
@Test
public void testReadProjectView() {
try {

View File

@ -0,0 +1,616 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.gcube.application.geoportal.common.model.document.Project;
import org.gcube.application.geoportalcommon.ConvertToDataValueObjectModel;
import org.gcube.application.geoportalcommon.ProjectDVBuilder;
import org.gcube.application.geoportalcommon.geoportal.GeoportalClientCaller;
import org.gcube.application.geoportalcommon.geoportal.ProjectsCaller;
import org.gcube.application.geoportalcommon.geoportal.UseCaseDescriptorCaller;
import org.gcube.application.geoportalcommon.shared.geoportal.materialization.GCubeSDIViewerLayerDV;
import org.gcube.application.geoportalcommon.shared.geoportal.materialization.innerobject.FilesetDV;
import org.gcube.application.geoportalcommon.shared.geoportal.materialization.innerobject.PayloadDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.ProjectDV;
import org.gcube.application.geoportalcommon.shared.geoportal.view.ProjectView;
import org.gcube.application.geoportalcommon.shared.geoportal.view.SectionView;
import org.gcube.application.geoportalcommon.shared.geoportal.view.SubDocumentView;
import org.gcube.application.geoportaldatamapper.Geoportal_JSON_Mapper;
import org.gcube.application.geoportaldatamapper.URLParserUtil;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.junit.Before;
import org.junit.Test;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.io.font.otf.Glyph;
import com.itextpdf.io.font.otf.GlyphLine;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfAnnotationBorder;
import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfOutputStream;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.Style;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Link;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.layout.properties.TextAlignment;
/**
* The Class Geoportal_Export_To_PDF_Tests.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Dec 5, 2022
*/
public class Geoportal_Export_To_PDF_Tests {
private static final int FONT_SIZE_SECTION_TITLE = 14;
private static final String GCUBE_CONFIG_PROPERTIES_FILENAME = "gcube_config.properties";
private static final float PARAGRAPH_FONT_SIZE = 9;
// APP Working Directory + /src/test/resources must be the location of
// gcube_config.properties
private static String gcube_config_path = String.format("%s/%s",
System.getProperty("user.dir") + "/src/test/resources", GCUBE_CONFIG_PROPERTIES_FILENAME);
private static String CONTEXT;
private static String TOKEN;
private UseCaseDescriptorCaller clientUCD;
private ProjectsCaller clientProjects;
// private static String PROFILE_ID = "concessioni-estere";
private static String PROFILE_ID = "profiledConcessioni";
private static String PROJECT_ID = "6384db0c308f5c28c5ee0a32"; // 63d011c4dcac4551b9a6b930
// //6442653ac6a0422d9e9042e0
// //6399de3ca0a4545420373251
// IMPORTANT!!!! #NB SET USERNAME = null to test PUBLIC ACCESS
private static String USERNAME = "francesco.mangiacrapa";
/**
* Read context settings.
*/
public static void readContextSettings() {
try (InputStream input = new FileInputStream(gcube_config_path)) {
Properties prop = new Properties();
// load a properties file
prop.load(input);
CONTEXT = prop.getProperty("CONTEXT");
TOKEN = prop.getProperty("TOKEN");
// get the property value and print it out
System.out.println("CONTEXT: " + CONTEXT);
System.out.println("TOKEN: " + TOKEN);
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* Gets the client.
*
* @return the client
*/
@Before
public void getClient() {
readContextSettings();
// assumeTrue(GCubeTest.isTestInfrastructureEnabled());
ScopeProvider.instance.set(CONTEXT);
SecurityTokenProvider.instance.set(TOKEN);
clientUCD = GeoportalClientCaller.useCaseDescriptors();
clientProjects = GeoportalClientCaller.projects();
}
/**
* Test read project view.
*/
@Test
public void testExportToPDF() {
try {
ScopeProvider.instance.set(CONTEXT);
SecurityTokenProvider.instance.set(TOKEN);
Project theProject = clientProjects.getProjectByID(PROFILE_ID, PROJECT_ID);
ProjectDVBuilder projectBuilder = ProjectDVBuilder.newBuilder().fullDocumentMap(true);
projectBuilder.relationships(true);
String logoD4GNA = "https://data.d4science.org/shub/E_dmhxT0ZReFpXQ1ZXZUp0M2pXUGhtTEZicHNyMGZUVTB4cTkyc2xqMXFSWmo2Q3o4dWl0dTBmY1p1VTdPN29KMQ==";
String profileTitle = "Indagine svolta in regime di Concessione";
String gisLink = "https://My GIS Link";
String poweredByD4Science = "https://data.d4science.org/shub/E_cndCWGYxbFc3QVBKUnFvS1g1dy9ULzNqLzB4SXVKMldhRUQzTjV3MmJUV0pjVUFnWndHNnJ4bGNtTHZTR1hlaA==";
System.out.println("project json: " + theProject.getTheDocument().toJson());
ProjectDV theProjectDV = ConvertToDataValueObjectModel.toProjectDV(theProject, projectBuilder);
ProjectView projectView = Geoportal_JSON_Mapper.loadProjectView(theProjectDV, CONTEXT, USERNAME);
// Geoportal_JSON_Mapper.prettyPrintProjectView(projectView);
// CREATING NEW PDF
// Initialize PDF document
PdfDocument pdf = new PdfDocument(new PdfWriter("iTextSTART.pdf"));
// Initialize document
Document document = new Document(pdf);
// Adding logo D4GNA
Image image = toImageFromLink(logoD4GNA, 70);
// image.setMaxHeight(150);
image.setFixedPosition(document.getLeftMargin(),
pdf.getDefaultPageSize().getHeight() - image.getImageHeight() + 90);
document.add(image);
// Project Name
PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
String projectTitle = "";
try {
projectTitle = (String) theProjectDV.getTheDocument().getFirstEntryOfMap().getValue();
} catch (Exception e) {
// TODO: handle exception
}
Text title = new Text(projectTitle).setFont(bold);
Style style = new Style();
style.setPaddingTop(20);
style.setTextAlignment(TextAlignment.LEFT);
Paragraph p = new Paragraph().add(title).addStyle(style).setFontSize(17);
document.add(p);
// Project Type
Text projectType = new Text(profileTitle).setFontColor(ColorConstants.WHITE)
.setTextAlignment(TextAlignment.CENTER).setFontSize(8);
Style marginLeft = new Style().setMarginLeft(10);
projectType.addStyle(marginLeft);
// Adding type
Paragraph preface = new Paragraph();
preface.setHorizontalAlignment(HorizontalAlignment.CENTER);
DeviceRgb rgbColor = new DeviceRgb(0, 60, 136);
preface.setBackgroundColor(rgbColor);
preface.add(projectType);
document.add(preface);
// GIS LINK
Link theLink = getLinkFromURL(gisLink, gisLink, 5);
theLink.setFontSize(7);
Paragraph p2 = new Paragraph().add(theLink);
document.add(p2);
for (SectionView section : projectView.getListSections()) {
document = appendSubDocumentToPDF(document, section, section.getListSubDocuments());
}
// TimeStamp
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
PdfFont font = PdfFontFactory.createFont(StandardFonts.COURIER_OBLIQUE);
Style style2 = new Style().setFont(font).setFontSize(8);
Paragraph pt = new Paragraph().add("Created at "+now.format(dtf)).addStyle(style2);
// pt.setFixedPosition(document.getLeftMargin() + 30, 50,
// document.getPdfDocument().getDefaultPageSize().getWidth() - 75);
pt.setMarginTop(30);
document.add(pt);
// Credits
Table tableCredits = getCredits(document, logoD4GNA, poweredByD4Science);
document.add(tableCredits);
document.close();
System.out.println("\n\n testReadProjectView terminated!!!");
} catch (Exception e) {
System.err.println("Error");
e.printStackTrace();
}
}
private Table getCredits(Document document, String logoD4GNA, String logoPoweredByD4Science) {
Table tableCredits = toTableFixedLayout(document, 4, false);
tableCredits.setBorder(Border.NO_BORDER);
tableCredits.setTextAlignment(TextAlignment.LEFT);
// tableCredits.setFixedLayout();
tableCredits.setFixedPosition(document.getLeftMargin() + 30, 15,
document.getPdfDocument().getDefaultPageSize().getWidth() - 75);
// Adding logo D4GNA
Image imageLogo = toImageFromLink(logoD4GNA, 40);
Cell cell1 = new Cell();
cell1.setBorder(Border.NO_BORDER);
cell1.add(imageLogo);
tableCredits.addCell(cell1);
// Adding LINK D4GNA
Cell cell2 = new Cell();
Link theLinkD4GNA = getLinkFromURL("https://gna.d4science.org/", "https://gna.d4science.org/", 0);
theLinkD4GNA.setFontSize(5);
Paragraph p3 = new Paragraph().add(theLinkD4GNA);
cell2.setBorder(Border.NO_BORDER);
cell2.add(p3);
tableCredits.addCell(cell2);
// Adding logo Powered By D4Science
Image poweredByLink = toImageFromLink(logoPoweredByD4Science, 80);
Cell cell3 = new Cell();
cell3.setBorder(Border.NO_BORDER);
cell3.add(poweredByLink);
tableCredits.addCell(cell3);
// Adding LINK d4science
Cell cell4 = new Cell();
Link theLinkD4Science = getLinkFromURL("https://www.d4science.org/", "https://www.d4science.org/", 0);
theLinkD4Science.setFontSize(5);
Paragraph p4 = new Paragraph().add(theLinkD4Science);
cell4.setBorder(Border.NO_BORDER);
cell4.add(p4);
tableCredits.addCell(cell4);
return tableCredits;
}
private static Document appendSubDocumentToPDF(Document document, SectionView sectionView,
List<SubDocumentView> subDocuments) {
try {
boolean displayAsGallery = false;
for (SubDocumentView subDocumentView : subDocuments) {
if (subDocumentView.getListImages() != null && subDocumentView.getListImages().size() > 0) {
System.out.println("Section with images: " + subDocumentView.getListImages());
displayAsGallery = true;
break;
}
}
boolean displayAsMapOfLayers = false;
for (SubDocumentView subDocumentView : subDocuments) {
if (subDocumentView.getListLayers() != null && subDocumentView.getListLayers().size() > 0) {
System.out.println("Section with layers: " + subDocumentView.getListLayers());
displayAsMapOfLayers = true;
break;
}
}
// Displaying the whole section as a Gallery
if (displayAsGallery) {
PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
Paragraph paragraph = new Paragraph().add(sectionView.getSectionTitle()).setFont(bold)
.setFontSize(FONT_SIZE_SECTION_TITLE);
// paragraph.setMarginTop(10);
document.add(new AreaBreak());
document.add(paragraph);
System.out.println("displayAsGallery the: " + sectionView);
for (SubDocumentView subDocumentView : subDocuments) {
JsonObject jsonObject = new JsonParser().parse(subDocumentView.getMetadataAsJSON())
.getAsJsonObject();
Table tableContainer = toTableFixedLayout(document, 2, true);
// tableContainer.setBorder(Border.NO_BORDER);
Table tableMeta = new Table(2);
tableMeta = jsonToTable(tableMeta, 1, "", jsonObject);
// tableMeta.setBorder(Border.NO_BORDER);
List<FilesetDV> files = subDocumentView.getListImages();
Table tableI = new Table(1);
// tableI.setTextAlignment(TextAlignment.CENTER);
// tableI.setBorder(Border.NO_BORDER);
if (files != null) {
for (FilesetDV fileset : files) {
// Paragraph paragraphInt = new Paragraph(fileset.getGcubeProfileFieldName());
List<Image> listLinks = toImages(fileset.getListPayload());
for (Image image : listLinks) {
image.setBorder(Border.NO_BORDER);
tableI.addCell(image);
}
}
}
tableContainer.addCell(tableMeta);
tableContainer.addCell(tableI);
document.add(tableContainer);
}
// Displaying the whole section as a Map of Layers
} else if (displayAsMapOfLayers) {
PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
Paragraph paragraph = new Paragraph().add(sectionView.getSectionTitle()).setFont(bold)
.setFontSize(FONT_SIZE_SECTION_TITLE);
// paragraph.setMarginTop(10);
document.add(new AreaBreak());
document.add(paragraph);
System.out.println("displayAsMapOfLayers the: " + sectionView);
for (SubDocumentView subDocumentView : subDocuments) {
JsonObject jsonObject = new JsonParser().parse(subDocumentView.getMetadataAsJSON())
.getAsJsonObject();
Table tableContainerL = toTableFixedLayout(document, 1, true);
Table tableMeta = new Table(2);
tableMeta = jsonToTable(tableMeta, 1, "", jsonObject);
List<GCubeSDIViewerLayerDV> layers = subDocumentView.getListLayers();
Table tableI = new Table(1);
if (layers != null) {
for (GCubeSDIViewerLayerDV gCubeLayer : layers) {
tableI.setTextAlignment(TextAlignment.CENTER);
String wmsLink = gCubeLayer.getWMSLink();
System.out.println("wmsLink: " + wmsLink);
wmsLink = URLParserUtil.setValueOfParameter("format", wmsLink, "image/png", true);
Image image = toImageFromLink(wmsLink, 250);
tableI.setTextAlignment(TextAlignment.CENTER);
tableI.setHorizontalAlignment(HorizontalAlignment.CENTER);
tableI.addCell(image);
}
}
tableContainerL.addCell(tableI);
tableContainerL.addCell(tableMeta);
document.add(tableContainerL);
}
} else {
PdfFont bold = PdfFontFactory.createFont(StandardFonts.TIMES_BOLD);
Paragraph paragraph = new Paragraph().add(sectionView.getSectionTitle()).setFont(bold)
.setFontSize(FONT_SIZE_SECTION_TITLE);
paragraph.setMarginTop(10);
document.add(paragraph);
System.out.println("displaying default the: " + sectionView);
for (SubDocumentView subDocumentView : subDocuments) {
JsonObject jsonObject = new JsonParser().parse(subDocumentView.getMetadataAsJSON())
.getAsJsonObject();
Table table = toTableFixedLayout(document, 2, false);
table = jsonToTable(table, 1, "", jsonObject);
int rows = table.getNumberOfRows();
for (int i = 1; i < rows; i++) {
Cell cell1 = table.getCell(i, 0);
cell1.setMinWidth(80);
// cell1.setMaxWidth(100);
}
document.add(table);
List<FilesetDV> files = subDocumentView.getListFiles();
if (files != null) {
for (FilesetDV fileset : files) {
Paragraph paragraphInt = new Paragraph(fileset.getGcubeProfileFieldName());
paragraphInt.setFontSize(PARAGRAPH_FONT_SIZE);
List<Link> listLinks = toPDFLinks(fileset.getListPayload(), 5);
for (Link anchor : listLinks) {
paragraphInt.add(anchor);
}
document.add(paragraphInt);
}
}
}
}
} catch (Exception e) {
System.out.println("Error on rendering the section: " + e.getMessage());
e.printStackTrace();
}
return document;
}
private static Table toTableFixedLayout(Document document, int column, boolean maxWidthToPageSize) {
Table table = new Table(column);
table.setFixedLayout();
if (maxWidthToPageSize)
table.setWidth(document.getPdfDocument().getDefaultPageSize().getWidth() - 75);
return table;
}
private static List<Image> toImages(List<PayloadDV> payloads) throws IOException {
List<Image> listImages = new ArrayList<Image>(payloads.size());
for (PayloadDV payloadDV : payloads) {
Image img = toImageFromLink(payloadDV.getLink(), 250);
if (img != null)
listImages.add(img);
}
return listImages;
}
private static Image toImageFromLink(String link, Integer maxWidth) {
Image img = null;
try {
ImageData data = ImageDataFactory.create(link);
img = new Image(data);
// img.setBorder(Border.NO_BORDER);
if (maxWidth != null)
img.setMaxWidth(maxWidth);
else
img.setAutoScaleWidth(true);
} catch (MalformedURLException e) {
// silent
}
return img;
}
private static List<Link> toPDFLinks(List<PayloadDV> payloads, Integer marginLeft) throws IOException {
List<Link> listLinks = new ArrayList<Link>(payloads.size());
for (PayloadDV payloadDV : payloads) {
Link theLink = getLinkFromURL(payloadDV.getName(), payloadDV.getLink(), 5);
listLinks.add(theLink);
}
return listLinks;
}
private static Link getLinkFromURL(String linkTxt, String url, Integer marginLeft) {
Link theLink = new Link(linkTxt, PdfAction.createURI(url));
theLink.setFontSize(PARAGRAPH_FONT_SIZE);
theLink.setFontColor(ColorConstants.BLUE);
theLink.getLinkAnnotation().setBorder(new PdfAnnotationBorder(0, 0, 0));
Style style = new Style();
if (marginLeft != null)
style.setMarginLeft(marginLeft);
theLink.addStyle(style);
return theLink;
}
protected class TextFooterEventHandler implements IEventHandler {
protected Document doc;
public TextFooterEventHandler(Document doc) {
this.doc = doc;
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfCanvas canvas = new PdfCanvas(docEvent.getPage());
Rectangle pageSize = docEvent.getPage().getPageSize();
canvas.beginText();
try {
canvas.setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA_OBLIQUE), 5);
} catch (IOException e) {
e.printStackTrace();
}
canvas.moveText(
(pageSize.getRight() - doc.getRightMargin() - (pageSize.getLeft() + doc.getLeftMargin())) / 2
+ doc.getLeftMargin(),
pageSize.getTop() - doc.getTopMargin() + 10)
.showText("this is a header")
.moveText(0,
(pageSize.getBottom() + doc.getBottomMargin()) - (pageSize.getTop() + doc.getTopMargin())
- 20)
.showText("this is a footer")
.endText()
.release();
}
}
/**
* convert json Data to structured Html text
*
* @param json
* @return string
*/
private static Table jsonToTable(Table table, int deep, String key, Object obj) {
try {
// System.out.println("obj is istance of: " + obj.getClass());
if (obj instanceof JsonObject) {
JsonObject jsonObject = (JsonObject) obj;
// String[] keys = JSONObject.getNames(jsonObject);
Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
if (entrySet.size() > 0) {
for (Map.Entry<String, JsonElement> entry : entrySet) {
// System.out.println("Adding entry: " + entry);
table = jsonToTable(table, deep++, entry.getKey(), entry.getValue());
}
}
} else if (obj instanceof JsonArray) {
JsonArray array = (JsonArray) obj;
for (int i = 0; i < array.size(); i++) {
// recursive call
String arrayKey = key;
if (i > 0)
arrayKey = "";
table = jsonToTable(table, deep++, arrayKey, array.get(i));
}
} else {
// System.out.println("Adding key: " + key);
// System.out.println("Adding obj: " + obj.toString());
Cell cell1 = createContentCell(2);
cell1.setFontColor(ColorConstants.GRAY);
// cell1.setMinWidth(100);
// cell1.setMaxWidth(150);
cell1.add(new Paragraph(key));
table.addCell(cell1);
// row.add(key);
Cell cell2 = createContentCell(2);
JsonElement value = (JsonElement) obj;
Paragraph content = new Paragraph(value.getAsString());
content.setTextAlignment(TextAlignment.JUSTIFIED);
cell2.add(content);
table.addCell(cell2);
}
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
private static Cell createContentCell(Integer paddingTop) {
Cell cell = new Cell();
cell.setBorder(Border.NO_BORDER);
cell.setTextAlignment(TextAlignment.LEFT);
if (paddingTop != null)
cell.setPaddingTop(paddingTop);
cell.setFontSize(PARAGRAPH_FONT_SIZE);
return cell;
}
}