2

I have an open QGIS 3.0 project with a layout called "plan_view1". There are numerous selected layers (>100) that I want to turn on one-by-one and print the "plan_view1" layout to a pdf.

This is my code:

def printpdfmulti(layoutname):
    selected_layers = qgis.utils.iface.layerTreeView().selectedLayers()
    projectInstance = QgsProject.instance()
    layoutmanager = projectInstance.layoutManager()
    layout = layoutmanager.layoutByName(layoutname) #Layout nameprojectInstance = QgsProject.instance()
    for layer in selected_layers:
        qgis.utils.iface.legendInterface().setLayerVisible(layer, True)
        exporter = QgsLayoutExporter(layout)
        exporter.exportToPdf("C://data//" + layer.name() + ".pdf", QgsLayoutExporter.PdfExportSettings() )
        qgis.utils.iface.legendInterface().setLayerVisible(layer, False)


printpdfmulti("plane_view1")

The error messsage I get is:

Traceback (most recent call last):
  File "C:\OSGEO4~1\apps\Python36\lib\code.py", line 91, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 13, in <module>
  File "<string>", line 7, in printpdfmulti
AttributeError: 'QgisInterface' object has no attribute 'legendInterface'

What have I done wrong? I know my python programming is still very rough on the edges.

2 Answers 2

1

Replace the following line:

qgis.utils.iface.legendInterface().setLayerVisible(layer, True)

with this:

QgsProject.instance().layerTreeRoot().findLayer(layer.id()).setItemVisibilityChecked(True)

And to switch the visibility off, replace True with False.

1

Thanks Joseph.

I made your suggested changes and I also made 2 other changes:

  1. Refresh: a layout.refresh() updated the legend

  2. File Name Cleanup: I removed any problem characters from the layer names so they would be valid filenames

Thanks for the help. The final working code is below.

def printpdfmulti(layoutname):
    selected_layers = qgis.utils.iface.layerTreeView().selectedLayers()
    projectInstance = QgsProject.instance()
    layoutmanager = projectInstance.layoutManager()
    layout = layoutmanager.layoutByName(layoutname) #Layout nameprojectInstance = QgsProject.instance()
    for layer in selected_layers:
        QgsProject.instance().layerTreeRoot().findLayer(layer.id()).setItemVisibilityChecked(True)
        layout.refresh()
        exporter = QgsLayoutExporter(layout)
        filename = "".join(i for i in layer.name() if i not in "\/:*?<>|")
        exporter.exportToPdf("C://data//" + filename + ".pdf", QgsLayoutExporter.PdfExportSettings() )
        QgsProject.instance().layerTreeRoot().findLayer(layer.id()).setItemVisibilityChecked(False)


printpdfmulti("plane_view1")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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