5

I need add a legend, banner and signature to my shp file which is exported in PDF.

My code:

HashMap<String, Object> params = new HashMap<>();
        params.put(ShapefileDataStoreFactory.URLP.key, URLs.fileToUrl(new File("D:/var/shp/poli_cercanos.shp")));
    DataStore ds = DataStoreFinder.getDataStore(params);
    SimpleFeatureCollection fc = ds.getFeatureSource(ds.getTypeNames()[0]).getFeatures();

MapContent mapContent = new MapContent();
mapContent.setTitle("Quickstart");
Style style = SLD.createSimpleStyle(fc.getSchema());
Layer layer = new FeatureLayer(fc, style);
mapContent.addLayer(layer);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

int w = 1000;
ReferencedEnvelope bounds = fc.getBounds();
int h = (int) (w * (bounds.getHeight() / bounds.getWidth()));
BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bufferedImage.createGraphics();

mapContent.getViewport().setMatchingAspectRatio(true);

mapContent.getViewport().setScreenArea(new Rectangle(Math.round(w), Math.round(h)));
mapContent.getViewport().setBounds(bounds);

g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

Rectangle outputArea = new Rectangle(w, h);

GTRenderer renderer = new StreamingRenderer();
LabelCacheImpl labelCache = new LabelCacheImpl();
Map<Object, Object> hints = renderer.getRendererHints();
if (hints == null) {
    hints = new HashMap<>();
}
hints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);
renderer.setRendererHints(hints);
renderer.setMapContent(mapContent);
renderer.paint(g2d, outputArea, bounds);
ImageIO.write(bufferedImage, "png", baos);

Document document = new Document(PageSize.A2, 20, 20, 20, 20);
PdfWriter.getInstance(document, new FileOutputStream("D:/var/shp/poli_cercanos.pdf"));
document.open();
Image image = Image.getInstance(baos.toByteArray());
document.add(image);
document.close();`

My pdf generates the following image from the shp file:

pdf content

Then the following would be to add a legend and a signature to the image, like this:

expected result

2

One of the joys of open source software is the easy you can "borrow" code from another project. GeoServer is built using GeoTools and can produce a legend graphic from a list of layers and styles. Much of the work for that can be found in BufferedImageLegendGraphicBuilder.

Once you have one or more legend images it's a simple case of learning how the iText PdfWriter works to lay out the boxes and text elements, probably with a table.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.