MichaIng / DietPi

Lightweight justice for your single-board computer!
https://dietpi.com/
GNU General Public License v2.0
4.72k stars 492 forks source link

DietPi-Software | Add CUPS printer server #3942

Closed Gill-Bates closed 3 years ago

Gill-Bates commented 3 years ago

Hey there,

I was looking for a way to print to a PDF from my iPhone. I made it with the Raspberry Pi and Dietpi without any problems:

First installing CUPS:

sudo apt install avahi-daemon cups python3-cups
cupsctl --remote-admin 
cupsctl --share-printers

The CUPS-Webinterface is listening on Port 631

Now it is important to create virtual PDF-Printer. There is a package for it, called printer-driver-cups-pdf - but this printer sucks (prints images in a poor resolution)! It's better to create a General Printer from scratch:

Stop the Service systemctl stop cups.services

nano /etc/cups/pdf-printer.conf

Copy & Paste straight forward ...

Important: the Output-Dir of the PDFs: AnonDirName /var/spool/cups-pdf/ANONYMOUS

#  cups-pdf.conf -- CUPS Backend Configuration (version 3.0.1, 2017-02-24)
#  18.09.2005, Volker C. Behr
#  volker@cups-pdf.de
#  http://www.cups-pdf.de
#
#
#  This code may be freely distributed as long as this header
#  is preserved. Changes to the code should be clearly indicated.
#
#  This code is distributed under the GPL.
#  (http://www.gnu.org/copyleft/gpl.html)
#
#  For more detailed licensing information see cups-pdf.c in the
#  corresponding version number.

###########################################################################
#                                                                         #
# This is the configuration file for CUPS-PDF. Values that are not set in #
# here will use the defaults. Changes take effect immediately without the #
# need for restarting any services.                                       #
#                                                                         #
# Take care not to add whitespaces at the end of a line!                  #
#                                                                         #
# Options are marked where they can be set (setting via PPD requires the  #
# PPD file that comes with CUPS-PDF to be used!).                         #
# Options passed via lpoptions that are not named for lpoptions here are  #
# ignored.                                                                #
# Options precedence is as follows:                                       #
# 1st: lpoptions                                                          #
# 2nd: PPD settings                                                       #
# 3rd: config file (this file)                                            #
# 4th: default values                                                     #
###########################################################################

###########################################################################
#                                                                         #
# Path Settings                                                           #
#                                                                         #
###########################################################################

### Key: Out (config)
##  CUPS-PDF output directory
##  special qualifiers:
##     ${HOME} will be expanded to the user's home directory
##     ${USER} will be expanded to the user name
##  in case it is an NFS export make sure it is exported without
##  root_squash!
##  on Ubuntu, the cupsd AppArmor profile needs to be updated
##  to match the output path as per instructions in LP:147551
### Default: /var/spool/cups-pdf/${USER}

Out ${HOME}/PDF

### Key: AnonDirName (config)
##  ABSOLUTE path for anonymously created PDF files
##  if anonymous access is disabled this setting has no effect
### Default: /var/spool/cups-pdf/ANONYMOUS

AnonDirName /var/spool/cups-pdf/ANONYMOUS

### Key: Spool (config)
##  CUPS-PDF spool directory - make sure there is no user 'SPOOL' on your
##  system or change the path
### Default: /var/spool/cups-pdf/SPOOL

#Spool /var/spool/cups-pdf/SPOOL

###########################################################################
#                                                                         #
# Filename Settings                                                       #
#                                                                         #
###########################################################################

### Key: Truncate (config, ppd, lpoptions)
##  truncate long filenames to a maximum of <Truncate> characters
##  this does not consider the full path to the output but only the filename
##  without the .pdf-extension or a job-id prefix (see 'Label')
##  the minimal value is 8
### Default: 64

#Truncate 64

### Key: Cut (config, lpoptions)
##  removing file name extensions before appending .pdf to output
##  extensions will only be removed if _both_ the following criteria are met:
##   - the extension (w/o the dot) is not longer than <Cut> characters
##   - the remaining filename has a minimal length of 1 character
##  set Cut to -1 in order to disable cutting
##  recommended values: pure UNIX environment : -1
##                      mixed environments    :  3
### Default: 3

#Cut 3

### Key: Label (config, ppd, lpoptions)
##  label all jobs with a unique job-id in order to avoid overwriting old
##  files in case new ones with identical names are created; always true for
##  untitled documents
##  0: label untitled documents only
##  1: label all documents with a preceeding "job_#-"
##  2: label all documents with a tailing "-job_#"
### Default: 0

#Label 0

### Key: TitlePref (config, ppd, lpoptions)
##  where to look first for a title when creating the output filename
##  (title in PS file or title on commandline):
##  0: prefer title from %Title statement in the PS file
##  1: prefer title passed via commandline
### Default: 0

#TitlePref 0

###########################################################################
#                                                                         #
# User Settings                                                           #
#                                                                         #
###########################################################################

### Key: AnonUser (config)
##  uid for anonymous PDF creation (this might be a security issue)
##  this setting has no influence on AnonDirName (see there)
##  set this to an empty value to disable anonymous
### Default: nobody

#AnonUser nobody

### Key: LowerCase (config)
##  This options allows to check user names given to CUPS-PDF additionally
##  against their lower case variants. This is necessary since in some
##  Windows environments only upper case user names are passed. Usually UNIX
##  user names are all lower case and it is save to use this option
##  but be aware that it can lead to mis-identifications in case
##  you have user names that differ only in upper/lower case.
##     check only against user name as passed to CUPS  : 0
##     check additionally against lower case user name : 1
### Default: 1

#LowerCase 1

### Key: UserPrefix (config)
##  some installations require a domain prefix added to the user name
##  leave empty for no prefix
### Default: <empty>

#UserPrefix

### Key: DirPrefix (config)
##  if a prefix was defined above this switch toggels whether to include
##  the prefix in the output directory's name (if not $HOME) or not
##  0: do not include, 1: include
### Default: 0

#DirPrefix 0

### Key: RemovePrefix (config)
##  some installation pass usernames with a prefix (usually a domain name)
##  if you do not want this prefix to be used by the ${USER} variable for
##  output directories put the part which is to be cut here
### Default: <empty>

#RemovePrefix

###########################################################################
#                                                                         #
# Security Settings                                                       #
#                                                                         #
###########################################################################

### Key: AnonUMask (config)
##  umask for anonymous output
##  these are the _inverse_ permissions to be granted
### Default: 0000

#AnonUMask 0000

### Key: UserUMask (config, lptoptions)
##  umask for user output of known users
##  changing this can introduce security leaks if confidential
##  information is processed!
### Default: 0077

#UserUMask 0077

### Key: Grp (config)
##  group cups-pdf is supposed to run as - this will also be the gid for all
##  created directories and log files
### Default: lp

Grp lpadmin

### Key: AllowUnsafeOptions (config)
##  DON'T CHANGE THIS SETTING UNLESS YOU ABSOLUTELY KNOW WHAT YOU ARE DOING
##  set to 1 in order to allow users to override any option - including
##  those that pose SEVERE SECURITY RISKS, set to 0 for full security
### Default: 0

#AllowUnsafeOptions 0

###########################################################################
#                                                                         #
# Log Settings                                                            #
#                                                                         #
###########################################################################

### Key: Log (config)
##  CUPS-PDF log directory
##  set this to an empty value to disable all logging
### Default: /var/log/cups

#Log /var/log/cups

### Key: LogType (config, ppd)
##  log-mode
##  1: errors
##  2: status (i.e. activity)
##  4: debug - this will generate a lot of log-output!
##  add up values to combine options, i.e. 7 is full logging
##  if logging is disabled these setting have no effect
### Default: 3

#LogType 3

###########################################################################
#                                                                         #
# PDF Conversion Settings                                                 #
#                                                                         #
###########################################################################

### Key: GhostScript (config)
##  location of GhostScript binary (gs)
##  MacOSX: for using pstopdf (recommended) set this to /usr/bin/pstopdf
##          or its proper location on your system
### Default: /usr/bin/gs

#GhostScript /usr/bin/gs

### Key: GSTmp (config)
##  location of temporary files during GhostScript operation
##  this must be user-writable like /var/tmp or /tmp !
### Default: /var/tmp

#GSTmp /var/tmp

### Key: GSCall (config)
## command line for calling GhostScript (!!! DO NOT USE NEWLINES !!!)
## MacOSX: for using pstopdf set this to %s %s -o %s %s
### Default: %s -q -dCompatibilityLevel=%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -sOutputFile="%s" -dAutoRotatePages=/PageByPage -dAutoFilterColorImages=false -dColorImageFilter=/FlateEncode -dPDFSETTINGS=/prepress -c .setpdfwrite -f %s

#GSCall %s -q -dCompatibilityLevel=%s -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -sOutputFile="%s" -dAutoRotatePages=/PageByPage -dAutoFilterColorImages=false -dColorImageFilter=/FlateEncode -dPDFSETTINGS=/prepress -c .setpdfwrite -f %s

### Key: PDFVer (config, ppd, lptopions)
##  PDF version to be created - can be "1.5", "1.4", "1.3" or "1.2"
##  MacOSX: for using pstopdf set this to an empty value
### Default: 1.4

#PDFVer 1.4

### Key: PostProcessing (config, lptoptions)
##  postprocessing script that will be called after the creation of the PDF
##  as arguments the filename of the PDF, the username as determined by
##  CUPS-PDF and the one as given to CUPS-PDF will be passed
##  the script will be called with user privileges
##  set this to an empty value to use no postprocessing
### Default: <empty>

#PostProcessing

###########################################################################
#                                                                         #
# Experimental Settings                                                   #
#   These settings activate experimental options. If you decide to use    #
#   them I would appreciate any feedback - including an 'ok' if they      #
#   work as expected - so I can eventually put them into the non-         #
#   experimental sections.                                                #
#                                                                         #
###########################################################################

### Key: DecodeHexStrings (config)
##  this option will try to decode hex strings in the title to allow
##  internationalized titles
##  (have a look at pstitleconv on www.cups-pdf.de for a suitable filter
##   for data from Windows clients)
##  0: disable, 1: enable
### Default: 0

DecodeHexStrings 1

### Key: FixNewlines (config)
##  this option will try to fix various unusal line delimiters (e.g.
##  form feeds)
##  especially useful when using non-Linux-generated files
##  0: disable, 1: enable
### Default: 0

#FixNewlines 0

Replacing the /etc/cups/printers.conf File:

# Printer configuration file for CUPS v2.2.10
# Written by cupsd
# DO NOT EDIT THIS FILE WHEN CUPSD IS RUNNING
<DefaultPrinter PDF>
UUID urn:uuid:eb0decc5-b6f5-38dc-46e7-a001c26b49d1
Info PDF
MakeModel Generic CUPS-PDF Printer (w/ options)
DeviceURI cups-pdf:/
State Idle
StateTime 1606057228
ConfigTime 1606056136
Type 8450124
Accepting Yes
Shared Yes
JobSheets none none
QuotaPeriod 0
PageLimit 0
KLimit 0
OpPolicy default
ErrorPolicy retry-job
Option pdftops-renderer pdftocairo
</DefaultPrinter>

Restart the Services systemctl restart cups.services

Then getting a Script which generates the Airprint-Deamon

wget https://raw.githubusercontent.com/tjfontaine/airprint-generate/master/airprint-generate.py
chmod 755 airprint-generate.py
mv AirPrint-*.service /etc/avahi/services
./airprint-generate.py -d /etc/avahi/services

Restart the Services systemctl restart avahi-daemon.service

Voilá: image

MichaIng commented 3 years ago

Many thanks for this. While we dropped Google Cloud Print support for v6.34 (due to service shutdown at end of the year), an alternative is highly appreciated.

While it finally is for Apple AirPrint clients, I guess it can be similarly configured to work with other clients? I wish there would be a directory to place multiple files for multiple printer definitions so that we can install CUPS as a basis and add/remove multiple printers/backends easily 🤔.

Joulinar commented 3 years ago

What about using plain cups? @MichaIng

MichaIng commented 3 years ago

Since I never used it, does it work OOTB with Windows and Android stock network print implementation?

I'm thinking further, if this works fine, it should be possible to set up a VPN for remove printing (outside of local network), as a native replacement for Google Cloud Print without any special client requirements.

ravenclaw900 commented 3 years ago

This article provides instructions on how to use CUPS OOTB with all platforms. You do seem to be able to use it with windows without samba, you just have to put in the server manually.

Joulinar commented 3 years ago

Cups, is working quite well on my Windows box. What I did is following

  1. apt update && apt install cups
  2. change following nano /etc/cups/cupsd.conf
    
    # Only listen for connections from the local machine.
    Listen 0.0.0.0:631
    Listen /run/cups/cups.sock

Restrict access to the server...

Order allow,deny Allow @Local

Restrict access to the admin pages...

<Location /admin> Order allow,deny Allow @Local

Restrict access to configuration files...

<Location /admin/conf> AuthType Default Require user @SYSTEM Order allow,deny Allow @Local


3. `systemctl restart cups.service`
4. access Cups via https://192.168.0.12:631/
5. my HP network printer was detected automatically
6. printer added as `HP_Color_LaserJet_MFP_M277dw`
7. Inside Windows added the printer manually as internet port
`http://192.168.0.12:631/printers/HP_Color_LaserJet_MFP_M277dw`
8. did a test print with success 👍 
9. printing job is visible inside cups

![picture](https://user-images.githubusercontent.com/47155374/100912328-999d5900-34d0-11eb-8ae7-b678bc565400.png)
MichaIng commented 3 years ago

Nice, I guess with help of Avahi daemon the printer can be found automatically via network printer search.

I think hence the problem with the AirPrint implementation is the manual /etc/cups/printers.conf replacement. The file says that it is auto-created/edited by CUPS service, likely based on config file and/or web UI choices. So I assume that overwriting this file will remove other added printers. So if this cannot be configured easily with the web UI, the config needs to be appended instead of overwritten, but in a careful way as I guess only one "DefaultPrinter" entry can exist at a time and of course it must not be doubled.

Joulinar commented 3 years ago

@MichaIng I guess issue on the first post is to create a PDF printer on cups.

I continued playing with it and had no issues printing a document using Adobe App on an iPhone SE. Printer was detected automatically correctly.

Android (Pixel4) was a little bit more tricky and thinks are not working ootb as on iOS. It was needed to install an additional app to be able to detect the CUPS printer.

ravenclaw900 commented 3 years ago

According to the article I posted above, you might be able to do it natively by going to Settings → Connected Devices → Connection Preferences → Printing → Default Print Service.

Joulinar commented 3 years ago

well default print service did not detect the CUPS printer

Waxhaw commented 3 years ago

well default print service did not detect the CUPS printer

You have to turn on the Avahi services so that printers are 'shared' and found via Bonjour. I actually work for a printer mfr and could rant pages on this to put everyone to sleep.

Here is a GREAT tool to help you 'sniff out' services being broadcasted on your network: http://www.tildesoft.com

If you're printer and Avahi services are running correctly and you've 'shared' the printer in CUPS via command line or the Web interface it will show up there.

That's a great tool to help you figure out if your Bonjour services and network are setup correctly.

Happy Printing!

Joulinar commented 3 years ago

@MichaIng should we add CUPS as printing solution into DietPi? It's not that difficult as it's an apt package. Most tricky thing is to perform changes on cupsd.conf as we would need to add specific settings into specific places. Or we replace the file with our own one :)

MichaIng commented 3 years ago

Jep, it's THE UNIX printing system, so should be added to cover stopped CloudPrint and other front-ends. G_CONFIG_INJECT allows to set and in case add settings below other lines, which works well in case of [section]-separated config files. But if it's too fragile/complicated we can use our own as well.

Joulinar commented 3 years ago

basically it's about changing LISTEN address, which should be easy, and to grant local access by adding Allow @Local into the 3 sections I posted above https://github.com/MichaIng/DietPi/issues/3942#issuecomment-737398666

MichaIng commented 3 years ago

Looks like Apache2 syntax, although there "Order" and "Allow" directives have been deprecated and replaced by "Require" 😄. Are parent location directives not inherited by sub directories, i.e. would the

Order allow,deny
Allow @Local

block not be sufficient in the root directory block only?

Joulinar commented 3 years ago

nope you will still get access denied on the admin page and need to allow it explicitly. On the other hand we could removed whole admin page section as it is covered already by root folder permissions

# Restrict access to the admin pages...
#<Location /admin>
#  Order allow,deny
#</Location>
MichaIng commented 3 years ago

So sub directories inherit directives from parent directories, as long as there is no separate <Location block for the sub directory defined? Trying to understand how it works 😄.

Joulinar commented 3 years ago

Yep I guess that's how it works

LexiconCode commented 3 years ago

I will be keeping my eye on this. Number of days ago I started tinkering with a raspberry pi W getting my label printer network connected. A work in progress.

The OS may need need to pull down drivers from the server samba for the printer.

See configuration of smb.conf

Joulinar commented 3 years ago

thx for sharing the guide. It give one good hint how to allow local access to cups

@MichaIng cupsctl --remote-admin will adjust /etc/cups/cupsd.conf as follow 😄

# Allow remote access
Port 631

<Location />
  # Allow remote administration...
  Order allow,deny
  Allow @LOCAL
</Location>

<Location /admin>
  # Allow remote administration...
  Order allow,deny
  Allow @LOCAL
</Location>

<Location /admin/conf>
  AuthType Default
  Require user @SYSTEM
  # Allow remote access to the configuration files...
  Order allow,deny
  Allow @LOCAL
</Location>

Means no need to tweak it from our end. At least as long as we don't want to have specific hardening setup.

at the end it is quite simple setup

  1. apt install cups
  2. cupsctl --remote-admin

btw, which software ID to use?

ravenclaw900 commented 3 years ago

Probably 187, as 186 will be taken up by IPFS, and DietPi-NordVPN was removed this release.

Joulinar commented 3 years ago

Ok will go with 187

MichaIng commented 3 years ago

I turned this issue into a CUPS request. I know there is more to add Airprint, but CUPS is a basis from where we can add more.

NiNo-213 commented 3 years ago

Hi dears, I´ve installed Dietpi current verion - all fine so far - tried to install CUPS - but somehow it didn´t worked for me. Must say, I´m not that familiar with programming etc. but interested to test and try. If there is any solution , you need testperson, I could help. let me know.

rgds

Joulinar commented 3 years ago

Cups is not yet available. It will be on next version 7.1. however you could try current beta which was made available same days ago. This way you could check out cups

NiNo-213 commented 3 years ago

ok noted - can give it a try for sure. btw whatr abt tis guidline?

Joulinar commented 3 years ago

whatr abt tis guidline?

What do you mean?

NiNo-213 commented 3 years ago

I mean - this issue topic is based on the missing cups incl. a guidline description ow Micha installed it, isn´t it? anyway, can´t find the beta you mentioned on the website, atleat for 32bit (for 64bit there is one but it won´t work with pi zero w, or?)

MichaIng commented 3 years ago

See the beta notes here including a link on how to apply. You do not need to flash a new image, it's like a regular update but to a different branch 😉.

Now sure what you mean with the guideline? Do you mean a documentation page for it? Joulinar added one (not yet online): https://github.com/MichaIng/DietPi-Docs/pull/445/files#diff-d3c037c2488c59a223aa4f44bffd4e31cd25844b9397c3778bb5fecd923ecef8 But I think we can extend it, at least a step-by-step instruction about how to add a local printer via web interface 🙂.

Joulinar commented 3 years ago

a very small Where Do I Begin? section is available on cups docs http://www.cups.org/doc/overview.html

NiNo-213 commented 3 years ago

Great - yes, I meant the instruction obviously. :-) I´ll check and try this one - if interested/required- will update accordingly. thanks for such prompt support and help.

MichaIng commented 3 years ago

Nice, probably it makes even more sense then to link this (additionally) below the web UI access info to have it more prominent. It's very short indeed but probably sufficient and we should try to avoid duplicating existing docs 😉.

Joulinar commented 3 years ago

@MichaIng are you able to add this directly on dev branch or should I open new PR on docs?

MichaIng commented 3 years ago

Done: https://github.com/MichaIng/DietPi-Docs/commit/f8203e5cac96c18b81dacd15dbe8eedd50b94c1b

NiNo-213 commented 3 years ago

Just an update - works like a charm - perfect!

MichaIng commented 3 years ago

Many thanks for testing and feedback 🙂!

LexiconCode commented 3 years ago

Any reason CUPS 2.2.10 version is being used versus the latest CUPS 2.3.3?

ravenclaw900 commented 3 years ago

Yes, CUPS is installed through APT, and the Debian repository (for Buster), only has 2.2.10. https://packages.debian.org/buster/cups

LexiconCode commented 3 years ago

This might be a nice enhancement depending on interest. https://github.com/OpenPrinting/cups-filters

Actually there implementation of cups is actually maintained. OpenPrinting CUPS and backwards compatible. website

A quick blurb from the wiki "In February 2007, Apple Inc. hired chief developer Michael Sweet and purchased the CUPS source code.[8] On December 20, 2019 Michael Sweet announced on his blog that he had left Apple.[9] In 2020, the OpenPrinting organization forked the project, with Michael Sweet continuing work on it.[10]" which explains the fork.

MichaIng commented 3 years ago

This seems to be part of the Debian cups package already: