@user_passes_test(using_unique_session)
def printplan(request, planid):
    """
    Print a static map of a plan.
    
    This template renders a static HTML document for use with xhtml2pdf.
    
    Parameters:
        request -- An HttpRequest, which includes the current user.
        planid -- The plan to edit.
        
    Returns:
        A rendered HTML page suitable for conversion to a PDF.
    """
    if not is_session_available(request):
        return HttpResponseRedirect('/')
        
    cfg = commonplan(request, planid)

    sha = hashlib.sha1()
    sha.update(str(planid) + str(datetime.now()))
    cfg['composite'] = '/reports/print-%s.jpg' % sha.hexdigest()
    cfg['prefix'] = 'http://%s' % request.META['SERVER_NAME']

    if request.method == 'POST':
        if not 'bbox' in request.REQUEST or \
            not 'geography_url' in request.REQUEST or \
            not 'geography_lyr' in request.REQUEST or \
            not 'district_url' in request.REQUEST or \
            not 'district_lyr' in request.REQUEST:
            logger.warning('Missing required "bbox", "geography_url", "geography_lyr", "district_url", or "districts_lyr" parameter.')
            return HttpResponseRedirect('../view/')

        height = 500*2
        if 'height' in request.REQUEST:
            height = int(request.REQUEST['height'])*2
        width = 1024*2
        if 'width' in request.REQUEST:
            width = int(request.REQUEST['width'])*2
        opacity = 0.8
        if 'opacity' in request.REQUEST:
            opacity = float(request.REQUEST['opacity'])

        full_legend = json.loads(request.REQUEST['legend'])

        cfg['geography_url'] = request.REQUEST['geography_url']
        cfg['geography_lyr'] = request.REQUEST['geography_lyr']
        cfg['district_url'] = request.REQUEST['district_url']
        cfg['district_lyr'] = request.REQUEST['district_lyr']
        cfg['geo_legend'] = full_legend['geo']
        cfg['geo_legend_title'] = full_legend['geotitle']
        cfg['dist_legend'] = full_legend['dist']
        cfg['dist_legend_title'] = full_legend['disttitle']
        cfg['plan'] = Plan.objects.get(id=int(request.REQUEST['plan_id']))
        cfg['printed'] = datetime.now()

        # use modestmaps to get the basemap
        bbox = request.REQUEST['bbox'].split(',')

        pt1 = Point(float(bbox[0]), float(bbox[1]), srid=3785)
        pt1.transform(SpatialReference('EPSG:4326'))
        ll = ModestMaps.Geo.Location(pt1.y, pt1.x)

        pt2 = Point(float(bbox[2]), float(bbox[3]), srid=3785)
        pt2.transform(SpatialReference('EPSG:4326'))
        ur = ModestMaps.Geo.Location(pt2.y, pt2.x)

        dims = ModestMaps.Core.Point(width, height)
        provider = ModestMaps.OpenStreetMap.Provider()
        basemap = ModestMaps.mapByExtent(provider, ll, ur, dims)

        # create basemap for compositing
        fullImg = basemap.draw()


        # geography layer
        provider = ModestMaps.WMS.Provider(cfg['geography_url'], {
            'LAYERS':cfg['geography_lyr'],
            'TRANSPARENT':'true',
            'SRS': 'EPSG:3785',
            'HEIGHT': 512,
            'WIDTH': 512
        })
        overlayImg = ModestMaps.mapByExtent(provider, ll, ur, dims).draw()

        # create an invert mask of the geography
        maskImg = ImageChops.invert(overlayImg)


        # district fill layer
        provider = ModestMaps.WMS.Provider(cfg['district_url'], {
            'LAYERS':cfg['district_lyr'],
            'TRANSPARENT':'false',
            'SRS': 'EPSG:3785',
            'SLD_BODY': request.REQUEST['district_sld'],
            'HEIGHT': 512,
            'WIDTH': 512
        })
        overlayImg = Image.blend(overlayImg, ModestMaps.mapByExtent(provider, ll, ur, dims).draw(), 0.5)

        # composite the overlay onto the base, using the mask (from geography)
        fullImg = Image.composite(fullImg, Image.blend(fullImg, overlayImg, opacity), maskImg)


        # district line & label layer
        provider = ModestMaps.WMS.Provider(cfg['district_url'], {
            'LAYERS':cfg['district_lyr'],
            'TRANSPARENT':'true',
            'SRS': 'EPSG:3785',
            'SLD_BODY': request.REQUEST['label_sld'],
            'HEIGHT': 512,
            'WIDTH': 512
        })
        overlayImg = ModestMaps.mapByExtent(provider, ll, ur, dims).draw()

        # create an invert mask of the labels & lines
        maskImg = ImageChops.invert(overlayImg)

        # composite the district labels on top of the composited basemap, geography & district areas
        fullImg = Image.composite(fullImg, Image.blend(fullImg, overlayImg, opacity), maskImg)

        # save
        fullImg.save(settings.WEB_TEMP + ('/print-%s.jpg' % sha.hexdigest()),'jpeg',quality=100)

        # render pg to a string
        t = loader.get_template('printplan.html')
        page = t.render(DjangoContext(cfg))
        result = StringIO.StringIO()

        # setting encoding='UTF-8' causes an exception. removing this for now,
        # as allowing the method to set an encoding itself fixes the problem.
        # we may need to find an alternate strategy if it finds encodings that
        # it isn't able to decipher.
        CreatePDF(page, result, show_error_as_pdf=True)

        response = HttpResponse(result.getvalue(), mimetype='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=plan.pdf'

        return response
   
    else:
        return HttpResponseRedirect('../view/')
dataset/ETHPy150Open PublicMapping/DistrictBuilder/django/publicmapping/redistricting/views.py/printplan/original