HP provides their printing and scanning solution for linux known as HP Linux Imaging and Printing software (HPLIP), which is mostly included with Ubuntu installation. However, sometimes printers do not work due to plugins not being present or other compatibility issues. In such case you have to install necessary plugins by running hp-plugin- HP plugins download and install utility. If that does not work or if hplip is not installed then you have to install/repair hplip as shown in this answer on HP Community.
Assuming hplip is present and working, open Terminal and type hp-plugin and follow the instructions on the wizard that pops up. This will download and install the HP plugins required. Once the installation is complete, the printer will work.
This has worked for me when my printer was detected but was not printing. Attached below is a screenshot which was taken after the plugin was installed.
Screenshot of Ubuntu Terminal with hp-plugin command
You can see the list of plugins here.