AirPrint to any printer (without official AirPrint support) using Ubuntu and iOS

This is an update of my previous AirPrint escapade to get AirPrint working with Ubuntu 12.04 and iOS / OSX using a generic printer. I'm still using the Epson SX600FW and SX610FW family which have both been great to date, I spent an hour updating the config to enable AirPrint compatibility. Read on... 


Setup
  • I use an Epson SX610FW which is a network printer connected wirelessly to a WRT-54GL router and my Ubuntu server. This can work with any printer attached to a Ubuntu machine.
  • iOS versions 4.0 and above
  • OSX 10.6 Snow Leopard and above
  • Tested with Ubuntu 12.04 and above, which acts as the AirPrint server

Here's what to do:


1. Add your printer to the Ubuntu server
  • Goto System > Administration > Printing & And click Add Printer.
  • Select ‘Network Printer’ and 'Find Network Printer'
  • For me Ubuntu then automatically found and installed the appropriate driver, your mileage may vary
  • Eventually click ‘Apply’ to finish.

 2. Check that CUPS is in installed, if not you will need to install CUPS. You will need to have a PDF filter working correctly. Debian (Ubuntu) seems to provide this out of the box with a CUPS install;
dpkg -s cups | grep Status
sudo apt-get install cups


3. Go into the CUPS interface which should be here: http://localhost:631/admin

Enable the following options:
  • Show printers shared by other systems
  • Share printers connected to this system
  • Allow printing from the Internet
  • Allow remote administration
  • Allow users to cancel any job (not just their own) 
Do not add your printer to CUPS using this interface, the "share printers connected to this system" does this.

4. Edit the CUPS configuration file;
sudo gedit /etc/cups/cupsd.conf

Add the following lines: 
ServerAlias *


Change the following lines:
Port Localhost:631 to Port 631
BrowseAllow to BrowseAllow All

5. Check that Avahi is installed, if not you will need to install Avahi-daemon;
dpkg -s Avahi-daemon | grep Status
sudo apt-get install avahi-daemon

6. Restart CUPS to get it to publish printer services. (AirPrint will not be using the CUPS-published services, but we will need them to recreate a manual service.)
sudo /etc/init.d/cups restart

7. Generate the AirPrint Avahi service files for CUPS printers. TJ Fontaine has created a great script that automates the creation of the service files see, the actual script is here airprint-generate script.
./airprint-generate.py  


8. Move the generated AirPrint Avahi services files to the Avahi folder;
sudo mv AirPrint-Epson-Stylus-SX600FW.service /etc/avahi/services/AirPrint-Epson-Stylus-SX600FW.service


9. Restart CUPS and Avahi;
sudo /etc/init.d/cups restart
sudo restart avahi-daemon

10. Add two new config files

sudo vi /usr/share/cups/mime/airprint.types
Contents:
#
# "$Id: $"
#
# AirPrint type
image/urf urf string(0,UNIRAST<00>)
#
# End of "$Id: $".
#


sudo vi /usr/share/cups/mime/airprint.convs
Contents:
#
# "$Id: $"
#
# AirPrint
# Updated list with minimal set 25 Sept
image/urf application/pdf 100 pdftoraster
#
# End of "$Id: $".
#




10. Print! on your iPhone/iPad, go into an application (Safari, for example), print, and search for printers. Your new printer definition should be in there.


Kudos to Ryan Finnie for his initial research and TJ Fontaine the great AirPrint services script.. TJ Fontaine's AirPrint services python script is below for reference in case the link dies. Be careful if you copy this, that you do not copy the HTML encoding:



#!/usr/bin/env python

"""
Copyright (c) 2010 Timothy J Fontaine 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import cups, os, optparse, re, urlparse
import os.path
from StringIO import StringIO

from xml.dom.minidom import parseString
from xml.dom import minidom

import sys

try:
    import lxml.etree as etree
    from lxml.etree import Element, ElementTree, tostring
except:
    try:
        from xml.etree.ElementTree import Element, ElementTree, tostring
        etree = None
    except:
        try:
            from elementtree import Element, ElementTree, tostring
            etree = None
        except:
            raise 'Failed to find python libxml or elementtree, please install one of those or use python >= 2.5'

XML_TEMPLATE = """



	_ipp._tcp
	_universal._sub._ipp._tcp
	631
	txtvers=1
	qtotal=1
	Transparent=T
	URF=none

"""

#TODO XXX FIXME
#ty=AirPrint Ricoh Aficio MP 6000
#Binary=T
#Duplex=T
#Copies=T


DOCUMENT_TYPES = {
    # These content-types will be at the front of the list
    'application/pdf': True,
    'application/postscript': True,
    'application/vnd.cups-raster': True,
    'application/octet-stream': True,
    'image/urf': True,
    'image/png': True,
    'image/tiff': True,
    'image/png': True,
    'image/jpeg': True,
    'image/gif': True,
    'text/plain': True,
    'text/html': True,

    # These content-types will never be reported
    'image/x-xwindowdump': False,
    'image/x-xpixmap': False,
    'image/x-xbitmap': False,
    'image/x-sun-raster': False,
    'image/x-sgi-rgb': False,
    'image/x-portable-pixmap': False,
    'image/x-portable-graymap': False,
    'image/x-portable-bitmap': False,
    'image/x-portable-anymap': False,
    'application/x-shell': False,
    'application/x-perl': False,
    'application/x-csource': False,
    'application/x-cshell': False,
}

class AirPrintGenerate(object):
    def __init__(self, host=None, user=None, port=None, verbose=False,
        directory=None, prefix='AirPrint-', adminurl=False):
        self.host = host
        self.user = user
        self.port = port
        self.verbose = verbose
        self.directory = directory
        self.prefix = prefix
        self.adminurl = adminurl
        
        if self.user:
            cups.setUser(self.user)
    
    def generate(self):
        if not self.host:
            conn = cups.Connection()
        else:
            if not self.port:
                self.port = 631
            conn = cups.Connection(self.host, self.port)
            
        printers = conn.getPrinters()
        
        for p, v in printers.items():
            if v['printer-is-shared']:
                attrs = conn.getPrinterAttributes(p)
                uri = urlparse.urlparse(v['printer-uri-supported'])

                tree = ElementTree()
                tree.parse(StringIO(XML_TEMPLATE.replace('\n', '').replace('\r', '').replace('\t', '')))

                name = tree.find('name')
                name.text = 'AirPrint %s @ %%h' % (p)

                service = tree.find('service')

                port = service.find('port')
                port_no = None
                if hasattr(uri, 'port'):
                  port_no = uri.port
                if not port_no:
                    port_no = self.port
                if not port_no:
                    port_no = cups.getPort()
                port.text = '%d' % port_no

                if hasattr(uri, 'path'):
                  rp = uri.path
                else:
                  rp = uri[2]
                
                re_match = re.match(r'^//(.*):(\d+)(/.*)', rp)
                if re_match:
                  rp = re_match.group(3)
                
                #Remove leading slashes from path
                #TODO XXX FIXME I'm worried this will match broken urlparse
                #results as well (for instance if they don't include a port)
                #the xml would be malform'd either way
                rp = re.sub(r'^/+', '', rp)
                
                path = Element('txt-record')
                path.text = 'rp=%s' % (rp)
                service.append(path)

                desc = Element('txt-record')
                desc.text = 'note=%s' % (v['printer-info'])
                service.append(desc)

                product = Element('txt-record')
                product.text = 'product=(GPL Ghostscript)'
                service.append(product)

                state = Element('txt-record')
                state.text = 'printer-state=%s' % (v['printer-state'])
                service.append(state)

                ptype = Element('txt-record')
                ptype.text = 'printer-type=%s' % (hex(v['printer-type']))
                service.append(ptype)

                pdl = Element('txt-record')
                fmts = []
                defer = []

                for a in attrs['document-format-supported']:
                    if a in DOCUMENT_TYPES:
                        if DOCUMENT_TYPES[a]:
                            fmts.append(a)
                    else:
                        defer.append(a)

                if 'image/urf' not in fmts:
                    sys.stderr.write('image/urf is not in mime types, %s may not be available on ios6 (see https://github.com/tjfontaine/airprint-generate/issues/5)%s' % (p, os.linesep))

                fmts = ','.join(fmts+defer)

                dropped = []

                # TODO XXX FIXME all fields should be checked for 255 limit
                while len('pdl=%s' % (fmts)) >= 255:
                    (fmts, drop) = fmts.rsplit(',', 1)
                    dropped.append(drop)

                if len(dropped) and self.verbose:
                    sys.stderr.write('%s Losing support for: %s%s' % (p, ','.join(dropped), os.linesep))

                pdl.text = 'pdl=%s' % (fmts)
                service.append(pdl)

                if self.adminurl:
                    admin = Element('txt-record')
                    admin.text = 'adminurl=%s' % (v['printer-uri-supported'])
                    service.append(admin)
                
                fname = '%s%s.service' % (self.prefix, p)
                
                if self.directory:
                    fname = os.path.join(self.directory, fname)
                
                f = open(fname, 'w')

                if etree:
                    tree.write(f, pretty_print=True, xml_declaration=True, encoding="UTF-8")
                else:
                    xmlstr = tostring(tree.getroot())
                    doc = parseString(xmlstr)
                    dt= minidom.getDOMImplementation('').createDocumentType('service-group', None, 'avahi-service.dtd')
                    doc.insertBefore(dt, doc.documentElement)
                    doc.writexml(f)
                f.close()
                
                if self.verbose:
                    sys.stderr.write('Created: %s%s' % (fname, os.linesep))

if __name__ == '__main__':
    parser = optparse.OptionParser()
    parser.add_option('-H', '--host', action="store", type="string",
        dest='hostname', help='Hostname of CUPS server (optional)', metavar='HOSTNAME')
    parser.add_option('-P', '--port', action="store", type="int",
        dest='port', help='Port number of CUPS server', metavar='PORT')
    parser.add_option('-u', '--user', action="store", type="string",
        dest='username', help='Username to authenticate with against CUPS',
        metavar='USER')
    parser.add_option('-d', '--directory', action="store", type="string",
        dest='directory', help='Directory to create service files',
        metavar='DIRECTORY')
    parser.add_option('-v', '--verbose', action="store_true", dest="verbose",
        help="Print debugging information to STDERR")
    parser.add_option('-p', '--prefix', action="store", type="string",
        dest='prefix', help='Prefix all files with this string', metavar='PREFIX',
        default='AirPrint-')
    parser.add_option('-a', '--admin', action="store_true", dest="adminurl",
        help="Include the printer specified uri as the adminurl")
    
    (options, args) = parser.parse_args()
    
    # TODO XXX FIXME -- if cups login required, need to add
    # air=username,password
    from getpass import getpass
    cups.setPasswordCB(getpass)
    
    if options.directory:
        if not os.path.exists(options.directory):
            os.mkdir(options.directory)
    
    apg = AirPrintGenerate(
        user=options.username,
        host=options.hostname,
        port=options.port,
        verbose=options.verbose,
        directory=options.directory,
        prefix=options.prefix,
        adminurl=options.adminurl,
    )
    
    apg.generate()

34 comments:

  1. This was the most straightforward guide I've found. Thanks so much! Finally printing from the iPad.

    ReplyDelete
  2. Thanks for this guide, worked great!

    ReplyDelete
  3. I cannot get this working. Working on an Ubuntu 13.04 server, the BrowseAllow option does not exist in cupsd.conf but "Browsing on" does. In the cups errorlog only the warning "CreateProfile failed: org.freedesktop.ColorManager.AlreadyExists:profile id 'HP-LaserJet-4050-Gray..' already exists" is shown. This might not be a problem (= warning not error)

    On my Ipad no Airprinter is found. IP and Web connection to the linuxsystem does work. server:631 shows the cups web interface.


    I had to change the "DefaultEncryption"to "IfRequested" because of the error "Unable to encrypt connection from 192.168.1.4 - A TLS packet with unexpected length was received" (192.168.1.4 is my Ipad trying to find an airprinter.

    cups version 1.6.2.
    Ubuntu 13.04 (up-to-date to 2 hours ago)
    printers: HP Laserjet 4050tn and Epson stylus RX 585
    From Linux both printers work correct.

    any ideas where to look next?

    Robbert.

    ReplyDelete
  4. I need help understanding why there are two printers showing up in AirPrint on my IOS device: One MX870LAN (which I can print from) and One AirPrint MX870LAN (which I can't print from) Any way to just have the working one published? It's confusing to others on my network. Thanks For posting by-the-way. It's a great tutorial!

    ReplyDelete
  5. I removed the AirPrint.... file from /etc/avahi/services and restarted avahi-daemon and then I had one printer published to my iOS devices

    ReplyDelete
  6. Hello,
    Worked well on old 10.04 ubuntu / ipad air (ios7) / HP Photosmart 4500

    Just few comments.

    At step 7 I had a warning saying that the image/urf was not present in the mime of cups and that it will probably not work on ios6. I continued the process and indeed it was not working on the first try.

    I then retry the step 7 and I got no warning. I continued until the end it is now working.
    So I suggest to do the step 10 (create the 2 additional configuration files) before to do the step 7.

    ReplyDelete
  7. Hello,
    Since ubuntu 14.04 (cups 1.7.2), Airprint is supported out of the box.
    I just opened cups settings (localhost:631) and tick "Share printers connected to this system". I restarted cupsd, and my printer magically appeared in my iPad.

    Hope this will help !
    Best

    ReplyDelete
  8. Found your article, works great with 18.04.1 Bionic Beaver. Thank you!

    ReplyDelete
  9. This won't works for my new windows 10 Laptop. Could you update this?

    ReplyDelete
  10. Model: MFCL2707DW; All-in-One Laser Printer; Monochrome. More Information: Help improve your efficiency with print and duplicate velocities of up to 30ppm a techunderworld about brother hl l2305w review

    ReplyDelete
  11. If you want any kind of assistance for Norton antivirus then contact at help.norton.com. they will provide you an efficient solution to your along with tips for better management of the software.

    ReplyDelete
  12. Thank™ you for sharing excellent information. ✆ Your website is so cool. I am impressed by the details that you have on this website ☞ It reveals how nicely you understand this subject. Bookmarked♠ this website page, will come back for extra articles. You, my friend, ROCK£ I found simply the info I already searched everywhere and simply could not come across. What a great website. Visit௹☞ Norton.com/setupoffice.com/setupTelstra supportPlumbers Near Me | office.com/setup | Nurton.com/nu16..

    ReplyDelete

  13. To install office setup you have to select the downloaded file otherwise insert the office setup CD disc. If you use the CD disc then you have to enter the Office Product Key for authorizing it. After selecting the downloaded file you have to run or setup this file on your computer.


    office.com/setup
    office.com/setup


    Install Norton Antivirus Protection To Your Windows, Mac Or Mobile Devices. Check out this Post to Get All Information About How You Can Redeem Your Norton Product Key and Get You Antivirus Activated In Few Easy steps.

    norton.com/setup
    norton.com/setup

    ReplyDelete

  14. Downloading process of the Office setup starts now. How to install Microsoft Office Setup? There are two methods to install Office setup in your PC - through a CD and by downloading. When you buy Office setup offline, then you have to install through a CD, and you get the setup file for installation if you get the setup online.

    Office.com/Setup

    ReplyDelete
  15. If you are looking for laser printer, then Brother is the place for you to look for it. If you’ve purchased a Brother Printer but don’t know how to setup the printer with your computer, then don’t worry. All you need is to give us a call for technical assistance and get a step-by-step solution to install your machine. Brother Printer Support is available 24/7 to help tackle unique problems you face with your brother printer.

    ReplyDelete


  16. the best site for Satta king, leak number & all record charts.We provide 100% fix number from direct Satta company which includes all famous games like Desawar, Gali Satta, Ghaziabad, Faridabad and other games of Satta Market(Satta matka) is also a simple game and essentially is a form of old lottery games.

    satta matka
    satta
    satta king
    satta matka results

    fmovies

    ReplyDelete
  17. Thanks for sharing such important information which is very useful .I really appreciate your way of work.
    123.hp.com/setup | HP Printer Assistant Software | 123.hp.com/Laserjet | 123.hp.com/envy5540

    ReplyDelete
  18. You could definitely see your skills in the article you write. The world hopes for even more passionate writers like you who aren’t afraid to say how they believe. All the time go after your heart.
    Factory Reset Computer

    ReplyDelete
  19. Are you looking for HP Printer Assistant. Visit Help Number USA to fix technical error. Get support from HP Printer Assistant!
    HP Printer Assistant download |
    HP Support Assistant download |
    How to change password in Outlook |
    How to reset apple id password on iPhone |

    ReplyDelete
  20. Thank for important information . I like your explanation of topic and ability to do work.I really found your post very interesting .
    Netflix Password Reset

    ReplyDelete
  21. It has been great to read this article it was quiet to be nice you every detail about the topic Thanks for sharing this article with us.
    How to reset mac computer

    ReplyDelete
  22. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
    How to reset your Wireless Router successfully

    ReplyDelete
  23. CRM Software is a strategy that helps streamline your employers qualified prospects, opportunities, appointments, earnings and service, by trying to keep buyer as centre of the process.

    Web Based CRM Software | Online CRM Software | CRM Software Development | CRM Software Company in India | CRM Software

    ReplyDelete
  24. Download Or Install Office Setup Step 1. Go to www.office.com/setup - Sign in, 2nd. Enter product key, and 3rd. we can also help you with office.com/setup online.

    ReplyDelete
  25. www.trendmicro.com/downloadme
    For Trend Micro Download , you must create a Trend Micro account from trend micro that can help you in smooth Trend Micro installation. Protect your systems and online data from multiple threats, including viruses, spyware, identity theft, malware, rootkits, Trojans, phishing attacks, ransomware, Adware, Worms, Bots, Horses, and other threats.You can activate the Trend Micro software by installing the Trend Micro download

    ReplyDelete
  26. the user must purchase a license of Avg antivirus from the retail store or online. Though download AVG software is the easiest process, your system must match the essential prerequisites of Avg antivirus. Once you will get AVG activation code and will create an AVG account , then you can install AVG with license number. install-avg-with-license-number | www.avg.com/activation | www.avg.com/retail

    ReplyDelete
  27. The Epson Printer Customer Service are prepared with a special technology called the Epson Advanced Printing Technology. This is the printer driver-software used in the Epson printer customer service number. With this cutting-edge technology, the Epsonprinters have a very useful characteristic which differentiates it from other printer manufacturers. Epson printer customer service phone number services are: support for setting up correctly support for slow printing support for print head issues support for poor quality print results For any kind of Epson printer issue linkup with Epson Printer Support Phone Number

    ReplyDelete
  28. Brother Printer Customer Service USA will fix all Brother Printer issues such as Setup, Installation, Drivers, wifi, configuration, any errors etc. Dial Brother Printer Support Phone Number USA.Brother printer are best for many reasons . Brother offers many printers with unbelievable functions. The team will assist you 24/7. Brother printers customer service number are globally known across the globe for providing top-quality printing experience, and these devices come equipped with a number of hi-tech features. Owing to their popularity, their user base is considerably high. For any kind of brother printer issue linkup with Brother Printer Support Phone Number

    ReplyDelete
  29. TurboTax, which is developed and launched by Intuit, is said to be the most trendsetting software that makes it easier for the users to compute and manage taxes and e-file returns. The software comes with various features, and as a result, it makes it easier for the users for calculating and filing the tax returns.
    turbotax Customer Service

    turbotax customer service number
    turbotax customer service phone number
    turbotax Support Phone Number

    ReplyDelete
  30. To Install AVG with license number , the user must purchase a license of Avg antivirus from the retail store or online. Though download AVG software is the easiest process, your system must match the essential prerequisites of Avg antivirus. Once you will get AVG activation code and will create an AVG account , then you can install AVG with license number. install-avg-with-license-number

    ReplyDelete