I recently encountered this problem and came up with this function to createLegend Layers.
/**
* Creates an array of LegendLayers of all layers currently visible in the map.
* @param {esri.Map} map
* @returns {esri.tasks.LegendLayer[]}
*/
function getLegendLayersFromMap(map) {
var layer, legendLayer, output = [];
for (var i = 0, l = map.layerIds.length; i < l; i += 1) {
layer = map.getLayer(map.layerIds);
if (layer.visible && layer.visibleAtMapScale) {
legendLayer = new LegendLayer();
legendLayer.layerId = layer.id;
if (layer.visibleLayers) {
legendLayer.subLayerIds = layer.visibleLayers;
}
output.push(legendLayer);
}
}
// Return null if the output array has no elements.
return output.length > 0 ? output : null;
}
// Sample call
var printParameters = new PrintParameters();
printParameters.map = map;
var template = new PrintTemplate();
template.format = "PDF";
// printUI is a custom class in my app that creates and manages the HTML UI for a print task form.
template.layout = printUI.getSelectedTempalteName();
template.layoutOptions = {
authorText:printUI.form.querySelector("input[name=author]").value,
titleText: printUI.form.querySelector("input[name=title]").value,
legendLayers: getLegendLayersFromMap(map)
};
printParameters.template = template;
printTask.execute(printParameters);