enhancement exporting layers

This commit is contained in:
Francesco Mangiacrapa 2023-11-13 18:18:10 +01:00
parent 9ecee3b2f6
commit 6523b98860
2 changed files with 331 additions and 66 deletions

16
pom.xml
View File

@ -110,6 +110,12 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.spatial.data</groupId>
<artifactId>geo-utility</artifactId>
<version>[1.0.0,2.0.0-SNAPSHOT)</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itext7-core -->
<dependency>
<groupId>com.itextpdf</groupId>
@ -124,11 +130,11 @@
<!-- <version>[0.4, 0.5)</version> -->
<!-- </dependency> -->
<dependency>
<groupId>org.imgscalr</groupId>
<artifactId>imgscalr-lib</artifactId>
<version>4.2</version>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.imgscalr</groupId> -->
<!-- <artifactId>imgscalr-lib</artifactId> -->
<!-- <version>4.2</version> -->
<!-- </dependency> -->
<!-- LOGGER -->
<dependency>

View File

@ -1,6 +1,4 @@
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
@ -11,14 +9,13 @@ import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import org.gcube.application.geoportal.common.model.document.Project;
import org.gcube.application.geoportalcommon.ConvertToDataValueObjectModel;
import org.gcube.application.geoportalcommon.ProjectDVBuilder;
@ -37,8 +34,12 @@ 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.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;
import org.gcube.spatial.data.geoutility.bean.WmsParameters;
import org.gcube.spatial.data.geoutility.shared.BBOX;
import org.gcube.spatial.data.geoutility.shared.wfs.WFSParameter;
import org.gcube.spatial.data.geoutility.wfs.WFSQueryBuilder;
//import org.imgscalr.Scalr;
//import org.imgscalr.Scalr.Method;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@ -72,6 +73,9 @@ import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.properties.HorizontalAlignment;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.renderer.CellRenderer;
import com.itextpdf.layout.renderer.DrawContext;
import com.itextpdf.layout.renderer.IRenderer;
/**
* The Class Geoportal_Export_To_PDF_Tests.
@ -97,7 +101,10 @@ public class Geoportal_Export_To_PDF_Tests {
// private static String PROFILE_ID = "concessioni-estere";
private static String PROFILE_ID = "profiledConcessioni";
private static String PROJECT_ID = "6388d9b3a1e60e66b7b5843a"; // "6384ae78308f5c28c5ee08aa"; //PRE
private static String PROJECT_ID = "646353c5d7fb4a4633022803"; // "6384ae78308f5c28c5ee08aa"; //PRE
//6388e4f8a1e60e66b7b584ac Ficocle-Cervia Vecchia
//6388d9b3a1e60e66b7b5843a
//646353c5d7fb4a4633022803 Villa Romana del Capo di Sorrento
// PROD
// 63d011c4dcac4551b9a6b930
@ -116,9 +123,11 @@ public class Geoportal_Export_To_PDF_Tests {
private static String MAP_BOX_GEOJSON_PARAMETER = "geojson({\"type\":\"Point\",\"coordinates\":%s})";
private static String MAP_BOX_ACCESS_TOKEN = "access_token=%s";
// private static String MAP_BOX_ACCESS_TOKEN = "access_token=%s";
private static String accessToken = "{ADD_ACCESS_TOKEN}";
private static String mapBoxAccessToken = "";
private static String mapSize = "500x300";
/**
* Read context settings.
@ -190,7 +199,7 @@ public class Geoportal_Export_To_PDF_Tests {
Document document = new Document(pdf);
// Adding logo D4GNA
Image image = toImageFromLink(logoD4GNA, 80, false);
Image image = toImageFromLink(logoD4GNA, 80);
// image.setMaxHeight(150);
image.setFixedPosition(document.getLeftMargin(),
pdf.getDefaultPageSize().getHeight() - image.getImageHeight() + 90);
@ -232,9 +241,9 @@ public class Geoportal_Export_To_PDF_Tests {
// Adding centroid MAP
String geoJSON = theProjectDV.getSpatialReference().getGeoJSON();
String downMapBoxImg = getMapBoxStaticMap(geoJSON, 7, accessToken);
String downMapBoxImg = linkToMarkerURLViaMapBoxStaticMap(geoJSON, 7, mapSize, mapBoxAccessToken);
Image backgroundImage = toImageFromLink(downMapBoxImg, 250, false);
Image backgroundImage = toImageFromLink(downMapBoxImg, 250);
Table tableI = new Table(1);
tableI.setTextAlignment(TextAlignment.CENTER);
tableI.addCell(backgroundImage);
@ -272,7 +281,17 @@ public class Geoportal_Export_To_PDF_Tests {
}
}
private static String getMapBoxStaticMap(String geoJSON, int zoom, String accessTokenValue) {
/**
* Link to marker URL via map box static map.
*
* @param geoJSON the geo JSON
* @param zoom the zoom
* @param widthXheight the width xheight
* @param accessTokenValue the access token value
* @return the string
*/
private static String linkToMarkerURLViaMapBoxStaticMap(String geoJSON, int zoom, String widthXheight,
String accessTokenValue) {
// String geoJSON = theProjectDV.getSpatialReference().getGeoJSON();
@ -288,13 +307,9 @@ public class Geoportal_Export_To_PDF_Tests {
zoom = 7;
jsonArray.put(jsonArray.length() - 1, zoom);
pointCoordinates = jsonArray.toString();
String accessToken = String.format(MAP_BOX_ACCESS_TOKEN, accessTokenValue);
//
String downMapBoxImg = String.format("%s/%s/%s/500x300?%s", MAP_BOX_STATIC_API_ENDPOINT, geojson,
pointCoordinates.replaceAll("\\[", "").replaceAll("\\]", ""), accessToken);
String downMapBoxImg = String.format("%s/%s/%s/%s?access_token=%s", MAP_BOX_STATIC_API_ENDPOINT, geojson,
pointCoordinates.replaceAll("\\[", "").replaceAll("\\]", ""), widthXheight, accessTokenValue);
System.out.println("DOWN IMAGE: " + downMapBoxImg);
@ -311,6 +326,41 @@ public class Geoportal_Export_To_PDF_Tests {
return null;
}
/**
* Link to map box static map.
*
* @param bbox the bbox
* @param widthXheight the width xheight
* @param accessTokenValue the access token value
* @return the string
*/
private static String linkToMapBoxStaticMap(String bbox, String widthXheight, String accessTokenValue) {
try {
String downMapBoxImg = String.format("%s/[%s]/%s?access_token=%s", MAP_BOX_STATIC_API_ENDPOINT, bbox,
widthXheight, accessTokenValue);
System.out.println("DOWN IMAGE: " + downMapBoxImg);
return downMapBoxImg;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* Gets the credits.
*
* @param document the document
* @param logoD4GNA the logo D 4 GNA
* @param logoPoweredByD4Science the logo powered by D 4 science
* @return the credits
*/
private Table getCredits(Document document, String logoD4GNA, String logoPoweredByD4Science) {
Table tableCredits = toTableFixedLayout(document, 4, false);
@ -320,7 +370,7 @@ public class Geoportal_Export_To_PDF_Tests {
tableCredits.setFixedPosition(document.getLeftMargin() + 30, 15,
document.getPdfDocument().getDefaultPageSize().getWidth() - 75);
// Adding logo D4GNA
Image imageLogo = toImageFromLink(logoD4GNA, 40, false);
Image imageLogo = toImageFromLink(logoD4GNA, 40);
Cell cell1 = new Cell();
cell1.setBorder(Border.NO_BORDER);
cell1.add(imageLogo);
@ -335,7 +385,7 @@ public class Geoportal_Export_To_PDF_Tests {
tableCredits.addCell(cell2);
// Adding logo Powered By D4Science
Image poweredByLink = toImageFromLink(logoPoweredByD4Science, 80, false);
Image poweredByLink = toImageFromLink(logoPoweredByD4Science, 80);
Cell cell3 = new Cell();
cell3.setBorder(Border.NO_BORDER);
cell3.add(poweredByLink);
@ -353,6 +403,14 @@ public class Geoportal_Export_To_PDF_Tests {
return tableCredits;
}
/**
* Append sub document to PDF.
*
* @param document the document
* @param sectionView the section view
* @param subDocuments the sub documents
* @return the document
*/
private static Document appendSubDocumentToPDF(Document document, SectionView sectionView,
List<SubDocumentView> subDocuments) {
try {
@ -401,7 +459,7 @@ public class Geoportal_Export_To_PDF_Tests {
if (files != null) {
for (FilesetDV fileset : files) {
// Paragraph paragraphInt = new Paragraph(fileset.getGcubeProfileFieldName());
List<Image> listLinks = toImages(fileset.getListPayload(), 250, false);
List<Image> listLinks = toImages(fileset.getListPayload(), 250);
for (Image image : listLinks) {
image.setBorder(Border.NO_BORDER);
tableI.addCell(image);
@ -432,28 +490,60 @@ public class Geoportal_Export_To_PDF_Tests {
Table tableMeta = new Table(2);
tableMeta = jsonToTable(tableMeta, 1, "", jsonObject);
List<GCubeSDIViewerLayerDV> layers = subDocumentView.getListLayers();
Table tableI = new Table(1);
Table tableI = new Table(2);
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/jpeg", true);
Image image = toImageFromLink(wmsLink, 250, false);
System.out.println("wmsLink(1): " + wmsLink);
wmsLink = URLParserUtil.setValueOfParameter("format", wmsLink, "image/png", true);
String bbox = URLParserUtil.extractValueOfParameterFromURL("bbox", wmsLink);
String wmsVersion = URLParserUtil.extractValueOfParameterFromURL("version", wmsLink);
/*
wmsLink = URLParserUtil.setValueOfParameter("format", wmsLink, "application/json", true);
String geoJSON = toStringFromLink(wmsLink);
String downMapBoxImg = getMapBoxStaticMap(geoJSON, 7, accessToken);
Image image = toImageFromLink(downMapBoxImg, 250, false);*/
tableI.setTextAlignment(TextAlignment.CENTER);
tableI.setHorizontalAlignment(HorizontalAlignment.CENTER);
// Cell cell = new Cell();
//// cell.add(backgroundImage);
// cell.add(image);
Integer expWidth = 600;
Integer expHeight = 600;
wmsLink = URLParserUtil.setValueOfParameter("width", wmsLink, expWidth+"", true);
wmsLink = URLParserUtil.setValueOfParameter("height", wmsLink, expHeight+"", true);
Image image = toImageFromLink(wmsLink, null);
System.out.println("wmsLink cell 1: " + wmsLink);
tableI.addCell(image);
BBOX.COORDINATE_FORMAT bboxFormat = wmsVersion.contains("1.3") ? BBOX.COORDINATE_FORMAT.YX
: BBOX.COORDINATE_FORMAT.XY;
BBOX theBBOX = new BBOX(bbox, bboxFormat);
double tolerance = 0.003;
double lowerXR = theBBOX.getLowerLeftX() - tolerance;
double lowerYR = theBBOX.getLowerLeftY() - tolerance;
double upperXR = theBBOX.getUpperRightX() + tolerance;
double upperYR = theBBOX.getUpperRightY() + tolerance;
String parmBBOX = BBOX.toBBOXString(new BBOX(lowerXR, lowerYR, upperXR, upperYR, ""),
bboxFormat);
//Layer with background color
String wmsLinkTol = URLParserUtil.setValueOfParameter("bbox", wmsLink, parmBBOX, false);
wmsLinkTol+="&TRANSPARENT=TRUE";
System.out.println("wmsLink cell 2: " + wmsLink);
Image image2 = toImageFromLink(wmsLinkTol, null, null);
//MapBox static as background
String linkToMapBox = linkToMapBoxStaticMap(parmBBOX, expWidth+"x"+expHeight, mapBoxAccessToken);
System.out.println("linkToMapBox: " + linkToMapBox);
Image backImg = toImageFromLink(linkToMapBox, null, null);
Cell mapCell = new Cell();
mapCell.setNextRenderer(new ImageBackgroundCellRenderer(mapCell, backImg));
mapCell.add(image2);
tableI.addCell(mapCell);
}
}
@ -506,7 +596,85 @@ public class Geoportal_Export_To_PDF_Tests {
return document;
}
private static class ImageBackgroundCellRenderer extends CellRenderer {
protected Image img;
public ImageBackgroundCellRenderer(Cell modelElement, Image img) {
super(modelElement);
this.img = img;
}
// If a renderer overflows on the next area, iText uses #getNextRenderer() method to create a new renderer for the overflow part.
// If #getNextRenderer() isn't overridden, the default method will be used and thus the default rather than the custom
// renderer will be created
@Override
public IRenderer getNextRenderer() {
return new ImageBackgroundCellRenderer((Cell) modelElement, img);
}
@Override
public void draw(DrawContext drawContext) {
img.scaleToFit(getOccupiedAreaBBox().getWidth(), getOccupiedAreaBBox().getHeight());
drawContext.getCanvas().addXObjectFittedIntoRectangle(img.getXObject(), getOccupiedAreaBBox());
super.draw(drawContext);
}
}
/**
* Wms link to WFS request.
*
* @param wmsLink the wms link
* @return the string
*/
private static String wmsLinkToWFSRequest(String wmsLink) {
String endpoint = wmsLink.substring(0, wmsLink.indexOf("?"));
WFSQueryBuilder builder = new WFSQueryBuilder();
HashMap<WFSParameter, String> defaultR = builder.getDefaultWFSGetFeatureRequest();
wmsLink = URLParserUtil.setValueOfParameter("format", wmsLink, "application/json", true);
defaultR.put(WFSParameter.TYPENAME,
URLParserUtil.extractValueOfParameterFromURL(WmsParameters.LAYERS.getParameter(), wmsLink));
String crs = URLParserUtil.extractValueOfParameterFromURL(WmsParameters.CRS.getParameter(), wmsLink);
if (crs != null && !crs.isEmpty())
defaultR.put(WFSParameter.CRS, crs);
String srs = URLParserUtil.extractValueOfParameterFromURL(WmsParameters.SRS.getParameter(), wmsLink);
if (srs != null && !srs.isEmpty())
defaultR.put(WFSParameter.SRSNAME, srs);
String version = URLParserUtil.extractValueOfParameterFromURL(WmsParameters.VERSION.getParameter(), wmsLink);
if (version != null && !version.isEmpty())
defaultR.put(WFSParameter.VERSION, version);
// String bbox = URLParserUtil.extractValueOfParameterFromURL(WmsParameters.BBOX.getParameter(), wmsLink);
// if(bbox!=null && !bbox.isEmpty())
defaultR.put(WFSParameter.BBOX, null); // all features of the layers
String cqlFilter = URLParserUtil.extractValueOfParameterFromURL(WmsParameters.CQL_FILTER.getParameter(),
wmsLink);
if (cqlFilter != null && !cqlFilter.isEmpty())
defaultR.put(WFSParameter.CQL_FILTER, cqlFilter);
defaultR.put(WFSParameter.OUTPUTFORMAT, "application/json");
String wfsURL = builder.buildWFSFeatureQuery(endpoint, defaultR);
System.out.println("wfsLink:" + wfsURL);
return wfsURL;
}
/**
* To table fixed layout.
*
* @param document the document
* @param column the column
* @param maxWidthToPageSize the max width to page size
* @return the table
*/
private static Table toTableFixedLayout(Document document, int column, boolean maxWidthToPageSize) {
Table table = new Table(column);
table.setFixedLayout();
@ -515,13 +683,20 @@ public class Geoportal_Export_To_PDF_Tests {
return table;
}
private static List<Image> toImages(List<PayloadDV> payloads, Integer maxWidth, boolean scaleImg)
throws IOException {
/**
* To images.
*
* @param payloads the payloads
* @param maxWidth the max width
* @return the list
* @throws IOException Signals that an I/O exception has occurred.
*/
private static List<Image> toImages(List<PayloadDV> payloads, Integer maxWidth) throws IOException {
List<Image> listImages = new ArrayList<Image>(payloads.size());
for (PayloadDV payloadDV : payloads) {
Image img = toImageFromLink(payloadDV.getLink(), maxWidth, scaleImg);
Image img = toImageFromLink(payloadDV.getLink(), maxWidth);
if (img != null)
listImages.add(img);
@ -531,21 +706,19 @@ public class Geoportal_Export_To_PDF_Tests {
}
private static Image toImageFromLink(String link, Integer maxWidth, boolean scaleImg) {
/**
* To image from link.
*
* @param link the link
* @param maxWidth the max width
* @return the image
*/
private static Image toImageFromLink(String link, Integer maxWidth) {
Image img = null;
try {
ImageData data = null;
if (scaleImg) {
final InputStream is = new URL(link).openStream();
BufferedImage inputImage = ImageIO.read(is);
BufferedImage out = simpleResizeImage(inputImage, maxWidth);
data = ImageDataFactory.create(out, Color.WHITE);
is.close();
} else {
data = ImageDataFactory.create(new URL(link));
}
data = ImageDataFactory.create(new URL(link));
img = new Image(data);
if (maxWidth != null)
@ -561,7 +734,68 @@ public class Geoportal_Export_To_PDF_Tests {
return img;
}
/**
* To image from link.
*
* @param link the link
* @param maxWidth the max width
* @return the image
*/
private static Image toImageFromLink(String link, Integer width, Integer height) {
Image img = null;
try {
ImageData data = null;
data = ImageDataFactory.create(new URL(link));
img = new Image(data);
if (width != null && height!=null) {
img.setWidth(width);
img.setHeight(height);
}
else {
img.setAutoScaleWidth(true);
//img.setAutoScaleHeight(true);
}
} catch (Exception e) {
// silent
e.printStackTrace();
}
return img;
}
/*
* private static Image toImageFromLink(String link, Integer maxWidth, boolean
* scaleImg) { Image img = null; try {
*
* ImageData data = null; if (scaleImg) { final InputStream is = new
* URL(link).openStream(); BufferedImage inputImage = ImageIO.read(is);
* BufferedImage out = simpleResizeImage(inputImage, maxWidth); data =
* ImageDataFactory.create(out, Color.WHITE); is.close(); } else { data =
* ImageDataFactory.create(new URL(link)); }
*
* img = new Image(data);
*
* if (maxWidth != null) img.setMaxWidth(maxWidth); else
* img.setAutoScaleWidth(true);
*
* } catch (Exception e) { // silent e.printStackTrace();
*
* }
*
* return img; }
*/
/**
* To string from link.
*
* @param link the link
* @return the string
*/
private static String toStringFromLink(String link) {
String text = null;
try {
@ -582,13 +816,21 @@ public class Geoportal_Export_To_PDF_Tests {
return text;
}
private static BufferedImage simpleResizeImage(BufferedImage originalImage, int targetWidth) throws Exception {
if (targetWidth > 0) {
return Scalr.resize(originalImage, Method.QUALITY, targetWidth);
}
return originalImage;
}
// private static BufferedImage simpleResizeImage(BufferedImage originalImage, int targetWidth) throws Exception {
// if (targetWidth > 0) {
// return Scalr.resize(originalImage, Method.QUALITY, targetWidth);
// }
// return originalImage;
// }
/**
* To PDF links.
*
* @param payloads the payloads
* @param marginLeft the margin left
* @return the list
* @throws IOException Signals that an I/O exception has occurred.
*/
private static List<Link> toPDFLinks(List<PayloadDV> payloads, Integer marginLeft) throws IOException {
List<Link> listLinks = new ArrayList<Link>(payloads.size());
@ -603,6 +845,14 @@ public class Geoportal_Export_To_PDF_Tests {
}
/**
* Gets the link from URL.
*
* @param linkTxt the link txt
* @param url the url
* @param marginLeft the margin left
* @return the link from URL
*/
private static Link getLinkFromURL(String linkTxt, String url, Integer marginLeft) {
Link theLink = new Link(linkTxt, PdfAction.createURI(url));
@ -617,9 +867,12 @@ public class Geoportal_Export_To_PDF_Tests {
}
/**
* convert json Data to structured Html text
*
* @param json
* convert json Data to structured Html text.
*
* @param table the table
* @param deep the deep
* @param key the key
* @param obj the obj
* @return string
*/
private static Table jsonToTable(Table table, int deep, String key, Object obj) {
@ -674,6 +927,12 @@ public class Geoportal_Export_To_PDF_Tests {
return table;
}
/**
* Creates the content cell.
*
* @param paddingTop the padding top
* @return the cell
*/
private static Cell createContentCell(Integer paddingTop) {
Cell cell = new Cell();
cell.setBorder(Border.NO_BORDER);