diff --git a/documentation/content/de/books/handbook/printing/_index.adoc b/documentation/content/de/books/handbook/printing/_index.adoc index 7c7d4a2568..d660309e13 100644 --- a/documentation/content/de/books/handbook/printing/_index.adoc +++ b/documentation/content/de/books/handbook/printing/_index.adoc @@ -1,736 +1,731 @@ --- title: Kapitel 9. Drucken part: Part II. Common Tasks prev: books/handbook/kernelconfig next: books/handbook/linuxemu showBookMenu: true weight: 12 path: "/books/handbook/printing/" --- [[printing]] = Drucken :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 9 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/printing/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] Trotz vieler Versuche es zu vermeiden, ist der Druck von Informationen auf Papier immer noch eine wichtige Funktion. Drucken hat zwei grundlegende Komponenten. Die Daten müssen an den Drucker gesendet werden, und zwar in einer Form, die der Drucker verstehen kann. [[printing-quick-start]] == Schnellstart Die grundlegende Druckfunktion kann schnell eingerichtet werden. Der Drucker muss lediglich fähig sein, normalen ASCII-Text zu drucken. Informationen zum Druck von anderen Dateien finden Sie in <>. [.procedure] **** . Erstellen Sie ein Verzeichnis zur Speicherung der Druckaufträge: + [source,shell] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... . Erstellen Sie als `root` die Datei [.filename]#/etc/printcap# mit folgendem Inhalt: + [.programlisting] .... lp:\ :lp=/dev/unlpt0:\ <.> :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :lf=/var/log/lpd-errs: .... + <.> Diese Zeile ist für einen Drucker, der an einem USB-Port angeschlossen ist.Für einen Drucker, der am parallelen oder "Drucker"-Port angeschlossen ist, verwenden Sie:Für einen Netzwerkdrucker verwenden Sie:Ersetzen Sie _network-printer-name_ durch den DNS-Namen des Netzwerkdruckers. . Aktivieren Sie `lpd` beim Systemstart, indem Sie folgende Zeile in [.filename]#/etc/rc.conf# hinzufügen: + [.programlisting] .... lpd_enable="YES" .... + Starten Sie den Dienst: + [source,shell] .... # service lpd start Starting lpd. .... + Drucken Sie eine Testseite: + [source,shell] .... # printf "1. Der Drucker kann drucken.\n2. Dies ist die zweite Zeile.\n" | lpr .... + [TIP] ==== Wenn die beiden Zeilen nicht am linken Rand starten und Sie einen "Treppeneffekt" beobachten, lesen Sie <>. ==== + Mit `lpr` können nun Textdateien gedruckt werden. Geben Sie den Dateinamen auf der Kommandozeile an oder lassen Sie `lpr` von einer Pipe lesen. + [source,shell] .... % lpr textfile.txt % ls -lh | lpr .... **** [[printing-connections]] == Druckerverbindungen Es gibt eine Vielzahl von Möglichkeiten, einen Drucker mit einem Rechner zu verbinden. Kleine Desktop-Drucker werden in der Regel mit dem USB-Anschluss verbunden, ältere Modelle nutzen oft die parallele Schnittstelle. Einige Drucker sind direkt mit einem Netzwerk verbunden, damit sie leichter von mehreren Rechnern benutzt werden können. Nur noch wenige Drucker verwenden einen seriellen Anschluss. FreeBSD unterstützt die folgenden Arten von Druckern: [[printing-connections-usb]] USB:: USB-Drucker können mit einem freien USB-Anschluss des Rechners verbunden werden. + Wenn FreeBSD einen USB-Drucker erkennt, werden zwei Gerätenamen erstellt: [.filename]#/dev/ulpt0# und [.filename]#/dev/unlpt0#. Beide Geräte leiten die Daten an den Drucker weiter. Nach jedem Druckauftrag wird der USB-Anschluss von [.filename]#ultp0# zurückgesetzt. Das Zurücksetzen kann bei einigen Druckern Probleme verursachen, daher wird in der Regel stattdessen [.filename]#unlpt0# verwendet, das den Anschluss nicht zurücksetzt. [[printing-connections-parallel]] Prallel (IEEE-1284):: Die parallele Schnittstelle ist [.filename]#/dev/lpt0#. Der Gerätename erscheint unabhängig davon, ob ein Drucker angeschlossen ist oder nicht. Eine automatische Erkennung findet nicht statt. + Die Hersteller haben sich weitgehend von diesem älteren Anschluss verabschiedet und auch viele Rechner haben keine parallele Schnittstelle mehr. Es existieren jedoch Adapter, um einen parallelen Drucker an einem USB-Port anzuschließen. Der Drucker wird dann wie ein USB-Drucker behandelt. Es können auch _Printserver_ verwendet werden, um parallele Drucker direkt mit einem Netzwerk zu verbinden. [[printing-connections-serial]] Seriell (RS-232):: Serielle Anschlüsse sind veraltet und werden außer in Nischenanwendungen nur noch selten verwendet. Die Kabel, Stecker und die erforderliche Verkabelung sind oft sehr unterschiedlich. + Der Gerätename für einen seriellen Anschlüsse ist [.filename]#/dev/cuau0# oder [.filename]#/dev/cuau1#. Es können auch USB-Adapter verwendet werden. Diese erscheinen als [.filename]#/dev/cuaU0#. + Damit mit dem Drucker kommuniziert werden kann, müssen einige Kommunikationsparameter bekannt sein. Zu den wichtigsten zählen die _Baudrate_ (BPS - Bits pro Sekunde) und die _Parität_. Diese Werte variieren, aber typische serielle Drucker verwenden eine Baudrate von 9600 und keine Parität. [[printing-connections-network]] Netzwerk:: Netzwerkdrucker werden direkt mit dem lokalen Netzwerk verbunden. + Der DNS-Name des Druckers muss bekannt sein. Wenn dem Drucker eine dynamische Adresse per DHCP zugeteilt wird, sollte das DNS automatisch aktualisiert werden, so dass der Drucker immer die richtige IP-Adresse hat. Um dieses Problem zu vermeiden, werden Netzwerkdruckern häufig statische IP-Adressen zugeteilt. + Die meisten Netzwerkdrucker verstehen Druckaufträge, die über das LPD-Protokoll empfangen werden. Sie können auch den Namen der Druckwarteschlange angeben. Einige Drucker verarbeiten die Daten unterschiedlich, je nachdem welche Warteschlange verwendet wird. Zum Beispiel druckt eine `Raw`-Warteschlange die Daten unverändert, während eine `Text`-Warteschlange den Text um Wagenrückläufe ergänzt. + Viele Netzwerkdrucker können auch Daten drucken, die direkt an Port 9100 gesendet werden. [[printing-connections-summary]] === Zusammenfassung Verkabelte Netzwerkdrucker drucken in der Regel am schnellsten und sind einfach einzurichten. Für den direkten Anschluss am Rechner wird USB wegen seiner Geschwindigkeit und Einfachheit bevorzugt. Parallele Verbindungen funktionieren, haben jedoch ihre Begrenzung in Bezug auf Kabellänge und Geschwindigkeit. Serielle Verbindungen sind schwieriger zu konfigurieren und die Verdrahtung unterscheidet sich zwischen den Modellen. Zudem müssen Baudrate und Parität bekannt sein. Glücklicherweise sind serielle Drucker selten geworden. [[printing-pdls]] == Gebräuchliche Seitenbeschreibungssprachen Daten, die an einen Drucker gesendet werden, müssen in einer Sprache verfasst sein, die der Drucker verstehen kann. Diese Sprachen werden Seitenbeschreibungssprachen oder Page Description Languages (PDL) genannt. [[print-pdls-ascii]] ASCII:: Schlichter ASCII-Text ist die einfachste Möglichkeit, um Daten an einen Drucker zu senden. Die Zeichen werden eins zu eins gedruckt: ein `A` in den Daten erscheint beim Druck als `A` auf dem Papier. Eine Formatierung ist nur bedingt verfügbar und es gibt keine Möglichkeit, eine Schriftart oder eine bestimmte Laufweite zu wählen. Die Einfachheit von schlichtem ASCII-Text bedeutet, dass Text ohne bzw. wenig Codierung oder Übersetzung gedruckt werden kann. Die gedruckte Ausgabe entspricht dem, was an den Drucker gesendet wurde. + Einige kostengünstige Drucker können keinen einfachen ASCII-Text drucken. Das macht sie in der Regel schwieriger einzurichten. [[print-pdls-postscript]] PostScript(R):: PostScript(R) ist fast das Gegenteil von ASCII. Anstelle von einfachem Text, besteht ein PostScript(R)-Programm aus einer Reihe von Anweisungen, die das endgültige Dokument generieren. Es können auch verschiedene Schriften und Grafiken benutzt werden. Diese Fähigkeiten haben jedoch ihren Preis. Das Programm, das die Seite generiert, muss zunächst erzeugt werden. Normalerweise wird dieses Programm durch die Anwendung erzeugt, so dass der Prozess für den Benutzer transparent bleibt. + Kostengünstige Drucker sind manchmal nicht kompatibel mit PostScript(R). [[print-pdls-pcl]] PCL (Printer Command Language):: PCL ist eine Erweiterung von ASCII. Es enthält Escape-Sequenzen für die Formatierung, Schriftauswahl und das Drucken von Grafiken. Viele Drucker bieten Unterstützung für PCL5, einige unterstützen auch das neuere PCL6 oder PCLXL. Die neueren Versionen sind Kombinationen von PCL5 und bieten eine schnellere Druckgeschwindigkeit. [[print-pdls-host-based]] Host-basiert:: Hersteller können die Kosten eines Druckers reduzieren, indem sie einen einfachen Prozessor und etwas Speicher verbauen. Diese Drucker sind nicht in der Lage normalen Text zu drucken. Stattdessen werden die Texte und Grafiken von einem Treiber auf dem Host-Rechner generiert und dann an den Drucker gesendet. Diese Drucker werden Host-basierte Drucker genannt. + Die Kommunikation zwischen dem Treiber und dem Drucker wird oft durch proprietäre oder nicht dokumentierte Protokolle realisiert, weshalb sie nur mit den gängigsten Betriebssystemen funktionieren. [[print-pdls-table]] === PostScript(R) in eine andere Sprache konvertieren Viele Anwendungen aus der Ports-Sammlung und FreeBSD Werkzeuge können PostScript(R) erzeugen. Die folgende Tabelle listet die verfügbaren Programme, um PostScript(R) in andere PDLs zu konvertieren: [[printing-pdls-ps-to-other-tbl]] .Ausgabe PDLs [cols="20%,20%,60%", options="header"] |=== <| Ausgabe PDL <| Generiert von <| Hinweis |PCL oder PCL5 |package:print/ghostscript9-base[] |`-sDEVICE=ljet4` für Schwarzweiß, `-sDEVICE=cljet5` für Farbe |PCLXL oder PCL6 |package:print/ghostscript9-base[] |`-sDEVICE=pxlmono` für Schwarzweiß, `-sDEVICE=pxlcolor` für Farbe |ESC/P2 |package:print/ghostscript9-base[] |`-sDEVICE=uniprint` |XQX |package:print/foo2zjs[] | |=== [[print-pdls-summary]] === Zusammenfassung Um die Konfiguration einfach zu halten, wählen Sie einen Drucker, der PostScript(R) oder auch PCL unterstützt. Mit package:print/ghostscript9-base[] können diese Drucker PostScript(R) nativ verstehen. Wenn der Drucker PostScript(R) oder PCL direkt unterstützt, können Sie auch sofort einfache ASCII-Textdateien drucken. Zeilenbasierte Drucker wie Tintenstrahldrucker unterstützen in der Regel kein PostScript(R) oder PCL. Dennoch können Sie ASCII-Textdateien drucken. package:print/ghostscript9-base[] unterstützt die Sprachen dieser Drucker. Jedoch ist der Druck von Grafiken auf diesen Druckern oft sehr langsam, da aufgrund der großen Menge an Daten übertragen und ausgedruckt werden müssen. Host-basierte Drucker sind oft schwieriger einzurichten. Einige Drucker können überhaupt nicht benutzt werden, da sie proprieräte PDLs verwerden. Solche Drucker sollten Sie nach Möglichkeit vermeiden. Die Beschreibungen vieler PDLs finden Sie auf http://www.undocprint.org/formats/page_description_languages[]. Spezielle PDLs, die von einigen Druckern verwendet werden finden Sie auf http://www.openprinting.org/printers[]. [[printing-direct]] == Direktes Drucken Für den gelegentlichen Druck können die Dateien auch direkt, ohne zusätzliche Einstellungen, an den Drucker gesendet werden. Zum Beispiel kann die Datei [.filename]#sample.txt# direkt an einen USB-Drucker gesendet werden: [source,shell] .... # cp sample.txt /dev/unlpt0 .... Ob Sie direkt auf einen Netzwerkdrucker drucken können, hängt von den Fähigkeiten des Druckers ab. Die meisten akzeptieren jedoch Druckaufträge auf Port 9100, die Sie mit man:nc[1] an den Drucker senden können. So drucken Sie die gleiche Datei auf einem Drucker mit dem DNS-Namen _netlaser_: [source,shell] .... # nc netlaser 9100 < sample.txt .... [[printing-lpd]] == LPD (Line Printer Daemon) Drucken im Hintergrund wird _Spooling_ genannt. Ein Spooler (Warteschlange) ermöglicht es dem Benutzer die Programme auf dem Rechner fortzusetzen, ohne warten zu müssen bis der Druckauftrag abgeschlossen ist. FreeBSD enthält den Spooler namens man:lpd[8]. Druckaufträge werden mit man:lpr[1] übermittelt. [[printing-lpd-setup]] === Konfiguration Erstellen Sie ein Verzeichnis zur Speicherung der Druckaufträge und setzen Sie die Berechtigungen auf diesem Verzeichnis, damit der Inhalt der Druckaufträge nicht von anderen Benutzern eingesehen werden kann: [source,shell] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... Drucker werden in [.filename]#/etc/printcap# angelegt. Ein Eintrag für einen Drucker enthält dessen Name, Anschluss sowie weitere Einstellungen. Erstellen Sie [.filename]#/etc/printcap# mit folgendem Inhalt: [.programlisting] .... lp:\ <.> :lp=/dev/unlpt0:\ <.> :sh:\ <.> :mx#0:\ <.> :sd=/var/spool/lpd/lp:\ <.> :lf=/var/log/lpd-errs: <.> .... <.> Der Name des Druckers. man:lpr[1] sendet Druckaufträge an den Drucker `lp`, es sei denn, ein anderer Drucker wird mit der Option `-P` angegeben. Der Standarddrucker sollte also `lp` genannt werden. <.> Der Anschluss, über den der Drucker verbunden ist. Ersetzen Sie diese Zeile mit dem entsprechenden, hier aufgeführten Verbindungstyp. <.> Unterdrückt das Drucken eines Deckblattes zu Beginn des Druckauftrags. <.> Die maximale Größe des Druckauftrags wird nicht begrenzt. <.> Das Verzeichnis zur Speicherung der Druckdaten. Jeder Drucker verwendet ein eigenes Verzeichnis. <.> Die Logdatei, in welche die Fehler des Druckers geschrieben werden. Nachdem Sie [.filename]#/etc/printcap# erstellt haben, verwenden Sie man:chkprintcap[8] um die Datei auf Fehler zu testen: [source,shell] .... # chkprintcap .... Beheben Sie alle gemeldeten Fehler, bevor Sie fortfahren. Aktivieren Sie man:lpd[8] in [.filename]#/etc/rc.conf#: [.programlisting] .... lpd_enable="YES" .... Starten Sie den Dienst: [source,shell] .... # service lpd start .... [[printing-lpd-lpr]] === Drucken mit man:lpr[1] Mit `lpr` werden Dokumente an den Drucker geschickt. Die Datei können Sie auf der Kommandozeile angeben, oder über eine Pipe an `lpr` schicken. Die beiden folgenden Kommandos sind gleichwertig, sie schicken den Inhalt von [.filename]#doc.txt# an den Standarddrucker: [source,shell] .... % lpr doc.txt % cat doc.txt | lpr .... Drucker können auch mit `-P` ausgewählt werden. Um auf einen Drucker namens _laser_ zu drucken: [source,shell] .... % lpr -Plaser doc.txt .... [[printing-lpd-filters]] === Filter In den bisher gezeigten Beispielen wurde lediglich eine Textdatei an den Drucker gesendet. Solange der Drucker den Inhalt dieser Dateien versteht, wird die Ausgabe korrekt gedruckt werden. Einige Drucker sind nicht in der Lage einfachen Text zu drucken. Es kann sogar sein, das die Eingabedatei gar keinen Text enthält. Mit Hilfe von _Filtern_ können Dateien übersetzt oder verarbeitet werden. Ein typischer Anwendungsfall ist die Umwandlung der Eingabedaten in ein Format, das der Drucker verstehen kann, wie bspw. PostScript(R) oder PCL. Filter können auch verwendet werden um zusätzliche Funktionen hinzuzufügen, wie bspw. Seitenzahlen oder das Hervorheben von Quellcode, um die Lesbarkeit zu verbessern. Die hier beschriebenen Filter werden _Eingabefilter_ oder auch _Textfilter_ genannt. Diese Filter übersetzen die eingehende Datei in verschiedene Formen. Werden Sie mit man:su[1] zu `root`, bevor Sie die Dateien erstellen. Filter werden in [.filename]#/etc/printcap# mit der Kennung `if=` festgelegt. Um [.filename]#/usr/local/libexec/lf2crlf# als Filter einzusetzen, bearbeiten Sie [.filename]#/etc/printcap# wie folgt: [.programlisting] .... lp:\ :lp=/dev/unlpt0:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :if=/usr/local/libexec/lf2crlf:\ <.> :lf=/var/log/lpd-errs: .... <.> `if=` identifiziert den Eingangsfilter, der auf den eingehenden Text angewendet werden soll. [TIP] ==== Der Backslash am Ende der Zeilen zeigt an, das ein Eintrag für einen Drucker wirklich nur eine Zeile ist, in der die einzelnen Einträge durch einen Doppelpunkt getrennt sind. Das Beispiel hätte man auch wie folgt schreiben können: [.programlisting] .... lp:lp=/dev/unlpt0:sh:mx#0:sd=/var/spool/lpd/lp:if=/usr/local/libexec/lf2crlf:lf=/var/log/lpd-errs: .... ==== [[printing-lpd-filters-stairstep]] ==== Den Treppeneffekt verhindern Typische Textdateien enthalten einen Zeilenvorschub am Ende jeder Zeile. Diese Zeilen erzeugen auf dem Drucker einen "Treppeneffekt": [.programlisting] .... A printed file looks like the steps of a staircase scattered by the wind .... Ein Filter kann Zeilenumbrüche in Wagenrückläufe und Zeilenumbrüche konvertieren. Erstellen Sie [.filename]#/usr/local/libexec/lf2crlf# mit folgendem Inhalt: [.programlisting] .... #!/bin/sh CR=$'\r' /usr/bin/sed -e "s/$/${CR}/g" .... Setzen Sie die Berechtigungen und machen Sie die Datei ausführbar: [source,shell] .... # chmod 555 /usr/local/libexec/lf2crlf .... Passen Sie [.filename]#/etc/printcap# an, so dass der neue Filter verwendet wird: [.programlisting] .... :if=/usr/local/libexec/lf2crlf:\ .... Drucken Sie nochmal die gleiche Datei, um den Filter zu testen. [[printing-lpd-filters-enscript]] ==== Mit package:print/enscript[] normalen Text auf PostScript(R)-Druckern drucken GNUEnscript wandelt Textdateien in formatiertes PostScript(R) um, die dann auf PostScript(R)-Druckern gedruckt werden können. Das Programm fügt auch Seitenzahlen und Zeilenumbrüche hinzu und stellt andere Funktionen bereit, um gedruckte Textdateien besser lesbar zu machen. Abhängig vom Papierformat können Sie entweder package:print/enscript-letter[] oder package:print/enscript-a4[] aus der Ports-Sammlung installieren. Erstellen Sie [.filename]#/usr/local/libexec/enscript# mit diesem Inhalt: [.programlisting] .... #!/bin/sh /usr/local/bin/enscript -o - .... Setzen Sie die Berechtigungen und machen Sie die Datei ausführbar: [source,shell] .... # chmod 555 /usr/local/libexec/enscript .... Bearbeiten Sie [.filename]#/etc/printcap# um den neuen Filter zu verwenden: [.programlisting] .... :if=/usr/local/libexec/enscript:\ .... Testen Sie den Filter, indem Sie eine einfache Textdatei drucken. [[printing-lpd-filters-ps2pcl]] ==== PostScript(R) auf PCL-Druckern drucken Viele Programme erzeugen PostScript(R)-Dokumente. Allerdings können kostengünstige Drucker oft nur Textdateien oder PCL verstehen. Dieser Filter wandelt PostScript(R)-Dateien in PCL um, bevor die Datei an den Drucker geschickt wird. Installieren Sie den Ghostscript PostScript(R) Interpreter package:print/ghostscript9-base[] aus der Ports-Sammlung. Erstellen Sie [.filename]#/usr/local/libexec/ps2pcl# mit diesem Inhalt: [.programlisting] .... #!/bin/sh /usr/local/bin/gs -dSAFER -dNOPAUSE -dBATCH -q -sDEVICE=ljet4 -sOutputFile=- - .... Setzen Sie die Berechtigungen und machen Sie die Datei ausführbar: [source,shell] .... # chmod 555 /usr/local/libexec/ps2pcl .... Die PostScript(R)-Eingabe wird von dem Skript erst in PCL umgewandelt, bevor es an den Drucker geschickt wird. Bearbeiten Sie [.filename]#/etc/printcap# um den neuen Filter zu verwenden: [.programlisting] .... :if=/usr/local/libexec/ps2pcl:\ .... Testen Sie den Filter mit einem kleinen PostScript(R)-Programm. [source,shell] .... % printf "%%\!PS \n /Helvetica findfont 18 scalefont setfont \ 72 432 moveto (PostScript printing successful.) show showpage \004" | lpr .... [[printing-lpd-filters-smart]] ==== Intelligente Filter Ein Filter kann sehr nützlich sein, wenn er die Eingabe erkennt und sie automatisch in ein für den Drucker verständliches Format umwandelt. Die ersten beiden Zeichen in einer PostScript(R)-Datei sind in der Regel `%!`. Ein Filter ist in der Lage diese beiden Zeichen zu erkennen. PostScript(R)-Dateien können unverändert an einen PostScript(R)-Drucker geschickt werden. Textdateien können, wie eben gezeigt, mit Enscript in PostScript(R) umgewandelt werden. Erstellen Sie [.filename]#/usr/local/libexec/psif# mit diesem Inhalt: [.programlisting] .... #!/bin/sh # # psif - Print PostScript or plain text on a PostScript printer # IFS="" read -r first_line first_two_chars=`expr "$first_line" : '\(..\)'` case "$first_two_chars" in %!) # %! : PostScript job, print it. echo "$first_line" && cat && exit 0 exit 2 ;; *) # otherwise, format with enscript ( echo "$first_line"; cat ) | /usr/local/bin/enscript -o - && exit 0 exit 2 ;; esac .... Setzen Sie die Berechtigungen und machen Sie die Datei ausführbar: [source,shell] .... # chmod 555 /usr/local/libexec/psif .... Bearbeiten Sie [.filename]#/etc/printcap# um den neuen Filter zu verwenden: [.programlisting] .... :if=/usr/local/libexec/psif:\ .... Um den Filter zu testen, drucken Sie PostScript(R)- und einfache Textdateien. -[[printing-lpd-filters-othersmart]] -==== Weitere intelligente Filter - -Einen Filter zu schreiben, der verschiedene Arten von Eingaben erkennen und formatieren kann, ist eine große Herausforderung. package:print/apsfilter[] aus der Ports-Sammlung ist auch ein intelligenter Filter, der Dutzende Dateitypen automatisch in eine für den Drucker verständliche PDL umwandeln kann. Weitere Details finden Sie auf http://www.apsfilter.org[]. - [[printing-lpd-queues]] === Mehrere Warteschlangen Die Einträge in [.filename]#/etc/printcap# sind nichts anderes als Definitionen von Warteschlangen. Für jeden Drucker können eine oder mehrere Warteschlangen definiert werden. Kombiniert mit Filtern bieten mehrere Warteschlangen eine bessere Kontrolle über die Druckaufträge. Als Beispiel dient ein vernetzter PostScript(R)-Laserdrucker in einem Büro. Die meisten Benutzer möchten einfache Textdateien drucken, aber ein paar fortgeschrittene Anwender sollen in der Lage sein, PostScript(R)-Dateien direkt zu drucken. Hierfür werden zwei Einträge für den Drucker in [.filename]#/etc/printcap# erstellt: [.programlisting] .... textprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/textprinter:\ :if=/usr/local/libexec/enscript:\ :lf=/var/log/lpd-errs: psprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/psprinter:\ :lf=/var/log/lpd-errs: .... Dokumente, die zum `textprinter` geschickt werden, werden wie im vorherigen Beispiel durch den Filter [.filename]#/usr/local/libexec/enscript# formatiert. Fortgeschrittene Anwender können PostScript(R)-Dateien direkt auf dem Drucker `psprinter` drucken, wo keine Filterung stattfindet. Mit mehreren Warteschlangen können Sie einen direkten Zugriff auf alle Arten von Druckerfunktionen zur Verfügung stellen. Ein Duplex-Drucker könnte zwei Warteschlangen verwenden, eine für den gewöhnlichen Druck und eine für den Duplexdruck. [[printing-lpd-monitor]] === Druckaufträge steuern und überwachen Es stehen verschiedene Programme zur Verfügung um Druckaufträge zu überwachen und den Druckbetrieb zu steuern. [[printing-lpd-monitor-lpq]] ==== man:lpq[1] man:lpq[1] zeigt den Status der Druckaufträge des Benutzers an. Druckaufträge anderer Benutzer werden nicht angezeigt. Dieser Befehl zeigt die anstehenden Druckaufträge eines Benutzers für einen Drucker an: [source,shell] .... % lpq -Plp Rank Owner Job Files Total Size 1st jsmith 0 (standard input) 12792 bytes .... Der folgende Befehl zeigt die anstehenden Druckaufträge eines Benutzers für alle Drucker an: [source,shell] .... % lpq -a lp: Rank Owner Job Files Total Size 1st jsmith 1 (standard input) 27320 bytes laser: Rank Owner Job Files Total Size 1st jsmith 287 (standard input) 22443 bytes .... [[printing-lpd-monitor-lprm]] ==== man:lprm[1] Mit man:lprm[1] können Druckaufträge gelöscht werden. Normale Benutzer dürfen lediglich ihre eigenen Aufträge löschen. `root` kann hingegen jeden beliebigen Auftrag löschen. Dieser Befehl löscht alle anstehenden Druckaufträge eines Druckers: [source,shell] .... # lprm -Plp - dfA002smithy dequeued cfA002smithy dequeued dfA003smithy dequeued cfA003smithy dequeued dfA004smithy dequeued cfA004smithy dequeued .... Mit dem folgenden Befehl löschen Sie einen bestimmten Druckauftrag. Benutzen Sie man:lpq[1], um die Nummer des Auftrags zu finden. [source,shell] .... % lpq Rank Owner Job Files Total Size 1st jsmith 5 (standard input) 12188 bytes % lprm -Plp 5 dfA005smithy dequeued cfA005smithy dequeued .... [[printing-lpd-monitor-lpc]] ==== man:lpc[8] Mit man:lpc[8] kann der Druckerstatus überprüft und verändert werden. `lpc` wird zusammen mit einem Kommando und optional mit einem Druckernamen aufgerufen. Mit `all` können alle Drucker angesprochen werden, auf denen das Kommando ausgeführt werden soll. Normale Benutzer können sich den Status mit man:lpc[8] ansehen. Nur `root` darf Kommandos ausführen, die den Status des Druckers verändern. Dieser Befehl zeigt den Status von allen Druckern an: [source,shell] .... % lpc status all lp: queuing is enabled printing is enabled 1 entry in spool area printer idle laser: queuing is enabled printing is enabled 1 entry in spool area waiting for laser to come up .... Der Drucker kann die Annahme neuer Druckaufträge verweigern. Anschließend sollen Aufträge wieder akzeptiert werden: [source,shell] .... # lpc stop lp lp: printing disabled # lpc start lp lp: printing enabled daemon started .... Starten Sie den Drucker nach einem Fehler neu: [source,shell] .... # lpc restart lp lp: no daemon to abort printing enabled daemon restarted .... Schalten Sie die Warteschlange aus und deaktivieren Sie den Druck. Sie können den Benutzern gleichzeitig eine Nachricht hinterlassen: [source,shell] .... # lpc down lp Ersatzteile werden am Montag ankommen lp: printer and queuing disabled status message is now: Ersatzteile werden am Montag ankommen .... Reaktivieren Sie den Drucker: [source,shell] .... # lpc up lp lp: printing enabled daemon started .... Weitere Kommandos und Optionen finden Sie in man:lpc[8]. [[printing-lpd-shared]] === Gemeinsam genutzte Drucker In Unternehmen und Schulen werden Drucker häufig von mehreren Benutzern genutzt. Es werden zusätzliche Funktionen angeboten, um die gemeinsame Nutzung von Druckern zu erleichtern. [[printing-shared-aliases]] ==== Aliase Der Druckername wird in der ersten Zeile von [.filename]#/etc/printcap# festgelegt. Weitere Namen oder _Aliase_ können nach dem Druckernamen hinzugefügt werden. Aliase werden vom Namen durch das Pipe-Zeichen `|` getrennt: [.programlisting] .... lp|repairsprinter|salesprinter:\ .... Anstelle des Druckernamens können Aliase verwendet werden. Zum Beispiel können Mitarbeiter der Verkaufsabteilung wie folgt auf ihren Drucker drucken: [source,shell] .... % lpr -Psalesprinter sales-report.txt .... Mitarbeiter der Reparaturabteilung drucken auf dem Drucker mit: [source,shell] .... % lpr -Prepairsprinter repairs-report.txt .... Alle Dokumente werden auf diesem einen Drucker gedruckt. Wenn die Verkaufsabteilung größer wird und die Abteilung einen eigenen Drucker benötigt, kann der Alias entfernt und für einen neuen Drucker verwendet werden. Die Mitarbeiter in beiden Abteilungen benutzen zum Drucken weiterhin die gleichen Befehle, nur dass die Aufträge der Verkaufsabteilung jetzt zum neuen Drucker gesendet werden. [[printing-shared-headers]] ==== Deckblätter Bei einem viel benutzten Drucker kann es für die Anwender schwierig sein, ihre Dokumente in einem großen Papierstapel wiederzufinden. Um dieses Problem zu lösen, können _Deckblätter_ verwendet werden. Dabei wird vor jedem Druckauftrag ein Deckblatt mit dem Benutzernamen und dem Dokumentnamen gedruckt. Deckblätter werden manchmal auch als _Banner_ oder _Trennseite_ bezeichnet. Das Aktivieren der Deckblätter hängt davon ab, ob der Drucker direkt über ein USB, paralleles oder serielles Kabel, oder über ein Netzwerk mit dem Rechner verbunden ist. Wenn der Drucker direkt verbunden ist, aktivieren Sie die Deckblätter durch Entfernen der Zeile `:sh:\` (Supress Header) in [.filename]#/etc/printcap#. Diese Deckblätter verwenden lediglich einen Zeilenvorschub für neue Zeilen. Einige Drucker benötigen den Filter [.filename]#/usr/shared/examples/printing/hpif# um den Treppeneffekt zu vermeiden. Der Filter konfiguriert PCL-Drucker so, dass sowohl Zeilenumbrüche als auch Zeilenvorschübe verwendet werden, wenn ein Zeilenvorschub empfangen wird. Für Netzwerkdrucker müssen Deckblätter auf dem Drucker selbst konfiguriert werden, da Einträge für Deckblätter in [.filename]#/etc/printcap# ignoriert werden. Die Einstellungen sind über einen Webbrowser zugänglich und stehen in der Regel auf der Hauptseite der Konfigurations-Webseite zur Verfügung. [[printing-lpd-references]] === Referenzen Beispieldateien: [.filename]#/usr/shared/examples/printing/#. Das _4.3BSD Line Printer Spooler Manual_, [.filename]#/usr/shared/doc/smm/07.lpd/paper.ascii.gz#. Manualpages: man:printcap[5], man:lpd[8], man:lpr[1], man:lpc[8], man:lprm[1], man:lpq[1]. [[printing-other]] == Andere Drucksysteme Neben dem in FreeBSD enthaltenen man:lpd[8] existieren noch weitere Drucksysteme. Diese Systeme bieten zusätzliche Funktionen und Unterstützung für andere Protokolle. [[printing-other-cups]] === CUPS (Common UNIX(R) Printing System) CUPS ist ein beliebtes Drucksystem, das für viele Betriebssysteme erhältlich ist. CUPS unter FreeBSD wird in einem separaten Artikel beschrieben: extref:{cups}[CUPS on FreeBSD]. [[printing-other-hplip]] === HPLIP Hewlett Packard stellt ein Drucksystem zur Verfügung, das viele ihrer Drucker unterstützt. Der Port heißt package:print/hplip[]. Die Webseite befindet sich unter http://hplipopensource.com/hplip-web/index.html[]. Der FreeBSD-Port kümmert sich um alle Details während der Installation. Informationen zur Konfiguration finden Sie unter http://hplipopensource.com/hplip-web/install/manual/hp_setup.html[]. [[printing-other-lprng]] === LPRng LPRng wurde als eine verbesserte Alternative zu man:lpd[8] entwickelt. Der Port heißt package:sysutils/LPRng[]. Weitere Informationen und Dokumentation finden Sie unter http://www.lprng.com/[]. diff --git a/documentation/content/en/books/handbook/printing/_index.adoc b/documentation/content/en/books/handbook/printing/_index.adoc index 5b02d9b04e..21b1faa92e 100644 --- a/documentation/content/en/books/handbook/printing/_index.adoc +++ b/documentation/content/en/books/handbook/printing/_index.adoc @@ -1,905 +1,898 @@ --- title: Chapter 11. Printing part: Part II. Common Tasks prev: books/handbook/kernelconfig next: books/handbook/linuxemu description: This chapter covers the printing system in FreeBSD tags: ["printing", "CUPS", "LPD", "PostScript", "PDLs", "HPLIP", "LPRng"] showBookMenu: true weight: 14 path: "/books/handbook/printing/" --- [[printing]] = Printing :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 11 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/printing/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] Putting information on paper is a vital function, despite many attempts to eliminate it. Printing has two basic components. The data must be delivered to the printer, and must be in a form that the printer can understand. [[printing-quick-start]] == Quick Start Basic printing can be set up quickly. The printer must be capable of printing plain `ASCII` text. For printing to other types of files, see <>. [.procedure] **** . Create a directory to store files while they are being printed: + [source,shell] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... + . As `root`, create [.filename]#/etc/printcap# with these contents: + [.programlisting] .... lp:\ lp=/dev/unlpt0:\ <.> sh:\ mx#0:\ sd=/var/spool/lpd/lp:\ lf=/var/log/lpd-errs: .... + <.> This line is for a printer connected to a `USB` port. + For a printer connected to a parallel or "printer" port, use: + [.programlisting] .... :lp=/dev/lpt0:\ .... + For a printer connected directly to a network, use: + [.programlisting] .... :lp=:rm=network-printer-name:rp=raw:\ .... + Replace _network-printer-name_ with the `DNS` host name of the network printer. + . Enable LPD by editing [.filename]#/etc/rc.conf#, adding this line: + [.programlisting] .... lpd_enable="YES" .... + Start the service: + [source,shell] .... # service lpd start Starting lpd. .... + . Print a test: + [source,shell] .... # printf "1. This printer can print.\n2. This is the second line.\n" | lpr .... + [TIP] ==== If both lines do not start at the left border, but "stairstep" instead, see <>. ==== + Text files can now be printed with `lpr`. Give the filename on the command line, or pipe output directly into `lpr`. + [source,shell] .... % lpr textfile.txt % ls -lh | lpr .... **** [[printing-connections]] == Printer Connections Printers are connected to computer systems in a variety of ways. Small desktop printers are usually connected directly to a computer's `USB` port. Older printers are connected to a parallel or "printer" port. Some printers are directly connected to a network, making it easy for multiple computers to share them. A few printers use a rare serial port connection. FreeBSD can communicate with all of these types of printers. [[printing-connections-usb]] `USB`:: `USB` printers can be connected to any available `USB` port on the computer. + When FreeBSD detects a `USB` printer, two device entries are created: [.filename]#/dev/ulpt0# and [.filename]#/dev/unlpt0#. Data sent to either device will be relayed to the printer. After each print job, [.filename]#ulpt0# resets the `USB` port. Resetting the port can cause problems with some printers, so the [.filename]#unlpt0# device is usually used instead. [.filename]#unlpt0# does not reset the USB port at all. [[printing-connections-parallel]] Parallel (`IEEE`-1284):: The parallel port device is [.filename]#/dev/lpt0#. This device appears whether a printer is attached or not, it is not autodetected. + Vendors have largely moved away from these "legacy" ports, and many computers no longer have them. Adapters can be used to connect a parallel printer to a `USB` port. With such an adapter, the printer can be treated as if it were actually a `USB` printer. Devices called _print servers_ can also be used to connect parallel printers directly to a network. [[printing-connections-serial]] Serial (RS-232):: Serial ports are another legacy port, rarely used for printers except in certain niche applications. Cables, connectors, and required wiring vary widely. + For serial ports built into a motherboard, the serial device name is [.filename]#/dev/cuau0# or [.filename]#/dev/cuau1#. Serial `USB` adapters can also be used, and these will appear as [.filename]#/dev/cuaU0#. + Several communication parameters must be known to communicate with a serial printer. The most important are _baud rate_ or `BPS` (Bits Per Second) and _parity_. Values vary, but typical serial printers use a baud rate of 9600 and no parity. [[printing-connections-network]] Network:: Network printers are connected directly to the local computer network. + The `DNS` hostname of the printer must be known. If the printer is assigned a dynamic address by `DHCP`, `DNS` should be dynamically updated so that the host name always has the correct `IP` address. Network printers are often given static `IP` addresses to avoid this problem. + Most network printers understand print jobs sent with the LPD protocol. A print queue name can also be specified. Some printers process data differently depending on which queue is used. For example, a `raw` queue prints the data unchanged, while the `text` queue adds carriage returns to plain text. + Many network printers can also print data sent directly to port 9100. [[printing-connections-summary]] === Summary Wired network connections are usually the easiest to set up and give the fastest printing. For direct connection to the computer, `USB` is preferred for speed and simplicity. Parallel connections work but have limitations on cable length and speed. Serial connections are more difficult to configure. Cable wiring differs between models, and communication parameters like baud rate and parity bits must add to the complexity. Fortunately, serial printers are rare. [[printing-pdls]] == Common Page Description Languages Data sent to a printer must be in a language that the printer can understand. These languages are called Page Description Languages, or PDLs. [[print-pdls-ascii]] `ASCII`:: Plain `ASCII` text is the simplest way to send data to a printer. Characters correspond one to one with what will be printed: an `A` in the data prints an `A` on the page. Very little formatting is available. There is no way to select a font or proportional spacing. The forced simplicity of plain `ASCII` means that text can be printed straight from the computer with little or no encoding or translation. The printed output corresponds directly with what was sent. + Some inexpensive printers cannot print plain `ASCII` text. This makes them more difficult to set up, but it is usually still possible. [[print-pdls-postscript]] PostScript(R):: PostScript(R) is almost the opposite of `ASCII`. Rather than simple text, a PostScript(R) program is a set of instructions that draw the final document. Different fonts and graphics can be used. However, this power comes at a price. The program that draws the page must be written. Usually this program is generated by application software, so the process is invisible to the user. + Inexpensive printers sometimes leave out PostScript(R) compatibility as a cost-saving measure. [[print-pdls-pcl]] `PCL` (Printer Command Language):: `PCL` is an extension of `ASCII`, adding escape sequences for formatting, font selection, and printing graphics. Many printers provide `PCL5` support. Some support the newer `PCL6` or `PCLXL`. These later versions are supersets of `PCL5` and can provide faster printing. [[print-pdls-host-based]] Host-Based:: Manufacturers can reduce the cost of a printer by giving it a simple processor and very little memory. These printers are not capable of printing plain text. Instead, bitmaps of text and graphics are drawn by a driver on the host computer and then sent to the printer. These are called _host-based_ printers. + Communication between the driver and a host-based printer is often through proprietary or undocumented protocols, making them functional only on the most common operating systems. [[print-pdls-table]] === Converting PostScript(R) to Other PDLs Many applications from the Ports Collection and FreeBSD utilities produce PostScript(R) output. This table shows the utilities available to convert that into other common PDLs: [[print-pdls-ps-to-other-tbl]] .Output PDLs [cols="1,1,1", frame="none", options="header"] |=== <| Output PDL <| Generated By <| Notes |`PCL` or `PCL5` |package:print/ghostscript9-base[] |`-sDEVICE=ljet4` for monochrome, `-sDEVICE=cljet5` for color |`PCLXL` or `PCL6` |package:print/ghostscript9-base[] |`-sDEVICE=pxlmono` for monochrome, `-sDEVICE=pxlcolor` for color |`ESC/P2` |package:print/ghostscript9-base[] |`-sDEVICE=uniprint` |`XQX` |package:print/foo2zjs[] | |=== [[print-pdls-summary]] === Summary For the easiest printing, choose a printer that supports PostScript(R). Printers that support `PCL` are the next preferred. With package:print/ghostscript9-base[], these printers can be used as if they understood PostScript(R) natively. Printers that support PostScript(R) or `PCL` directly almost always support direct printing of plain `ASCII` text files also. Line-based printers like typical inkjets usually do not support PostScript(R) or `PCL`. They often can print plain `ASCII` text files. package:print/ghostscript9-base[] supports the PDLs used by some of these printers. However, printing an entire graphic-based page on these printers is often very slow due to the large amount of data to be transferred and printed. Host-based printers are often more difficult to set up. Some cannot be used at all because of proprietary PDLs. Avoid these printers when possible. Descriptions of many PDLs can be found at http://www.undocprint.org/formats/page_description_languages[]. The particular `PDL` used by various models of printers can be found at http://www.openprinting.org/printers[]. [[printing-direct]] == Direct Printing For occasional printing, files can be sent directly to a printer device without any setup. For example, a file called [.filename]#sample.txt# can be sent to a `USB` printer: [source,shell] .... # cp sample.txt /dev/unlpt0 .... Direct printing to network printers depends on the abilities of the printer, but most accept print jobs on port 9100, and man:nc[1] can be used with them. To print the same file to a printer with the `DNS` hostname of _netlaser_: [source,shell] .... # nc netlaser 9100 < sample.txt .... [[printing-lpd]] == LPD (Line Printer Daemon) Printing a file in the background is called _spooling_. A spooler allows the user to continue with other programs on the computer without waiting for the printer to slowly complete the print job. FreeBSD includes a spooler called man:lpd[8]. Print jobs are submitted with man:lpr[1]. [[printing-lpd-setup]] === Initial Setup A directory for storing print jobs is created, ownership is set, and the permissions are set to prevent other users from viewing the contents of those files: [source,shell] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... Printers are defined in [.filename]#/etc/printcap#. An entry for each printer includes details like a name, the port where it is attached, and various other settings. Create [.filename]#/etc/printcap# with these contents: [.programlisting] .... lp:\ <.> :lp=/dev/unlpt0:\ <.> :sh:\ <.> :mx#0:\ <.> :sd=/var/spool/lpd/lp:\ <.> :lf=/var/log/lpd-errs: <.> .... <.> The name of this printer. man:lpr[1] sends print jobs to the `lp` printer unless another printer is specified with `-P`, so the default printer should be named `lp`. <.> The device where the printer is connected. Replace this line with the appropriate one for the connection type shown here. <.> Suppress the printing of a header page at the start of a print job. <.> Do not limit the maximum size of a print job. <.> The path to the spooling directory for this printer. Each printer uses its own spooling directory. <.> The log file where errors on this printer will be reported. After creating [.filename]#/etc/printcap#, use man:chkprintcap[8] to test it for errors: [source,shell] .... # chkprintcap .... Fix any reported problems before continuing. Enable man:lpd[8] in [.filename]#/etc/rc.conf#: [.programlisting] .... lpd_enable="YES" .... Start the service: [source,shell] .... # service lpd start .... [[printing-lpd-lpr]] === Printing with man:lpr[1] Documents are sent to the printer with `lpr`. A file to be printed can be named on the command line or piped into `lpr`. These two commands are equivalent, sending the contents of [.filename]#doc.txt# to the default printer: [source,shell] .... % lpr doc.txt % cat doc.txt | lpr .... Printers can be selected with `-P`. To print to a printer called _laser_: [source,shell] .... % lpr -Plaser doc.txt .... [[printing-lpd-filters]] === Filters The examples shown so far have sent the contents of a text file directly to the printer. As long as the printer understands the content of those files, output will be printed correctly. Some printers are not capable of printing plain text, and the input file might not even be plain text. _Filters_ allow files to be translated or processed. The typical use is to translate one type of input, like plain text, into a form that the printer can understand, like PostScript(R) or `PCL`. Filters can also be used to provide additional features, like adding page numbers or highlighting source code to make it easier to read. The filters discussed here are _input filters_ or _text filters_. These filters convert the incoming file into different forms. Use man:su[1] to become `root` before creating the files. Filters are specified in [.filename]#/etc/printcap# with the `if=` identifier. To use [.filename]#/usr/local/libexec/lf2crlf# as a filter, modify [.filename]#/etc/printcap# like this: [.programlisting] .... lp:\ :lp=/dev/unlpt0:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :if=/usr/local/libexec/lf2crlf:\ <.> :lf=/var/log/lpd-errs: .... <.> `if=` identifies the _input filter_ that will be used on incoming text. [TIP] ==== The backslash _line continuation_ characters at the end of the lines in [.filename]#printcap# entries reveal that an entry for a printer is really just one long line with entries delimited by colon characters. An earlier example can be rewritten as a single less-readable line: [.programlisting] .... lp:lp=/dev/unlpt0:sh:mx#0:sd=/var/spool/lpd/lp:if=/usr/local/libexec/lf2crlf:lf=/var/log/lpd-errs: .... ==== [[printing-lpd-filters-stairstep]] ==== Preventing Stairstepping on Plain Text Printers Typical FreeBSD text files contain only a single line feed character at the end of each line. These lines will "stairstep" on a standard printer: [.programlisting] .... A printed file looks like the steps of a staircase scattered by the wind .... A filter can convert the newline characters into carriage returns and newlines. The carriage returns make the printer return to the left after each line. Create [.filename]#/usr/local/libexec/lf2crlf# with these contents: [.programlisting] .... #!/bin/sh CR=$'\r' /usr/bin/sed -e "s/$/${CR}/g" .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/lf2crlf .... Modify [.filename]#/etc/printcap# to use the new filter: [.programlisting] .... :if=/usr/local/libexec/lf2crlf:\ .... Test the filter by printing the same plain text file. The carriage returns will cause each line to start at the left side of the page. [[printing-lpd-filters-enscript]] ==== Fancy Plain Text on PostScript(R) Printers with package:print/enscript[] GNUEnscript converts plain text files into nicely-formatted PostScript(R) for printing on PostScript(R) printers. It adds page numbers, wraps long lines, and provides numerous other features to make printed text files easier to read. Depending on the local paper size, install either package:print/enscript-letter[] or package:print/enscript-a4[] from the Ports Collection. Create [.filename]#/usr/local/libexec/enscript# with these contents: [.programlisting] .... #!/bin/sh /usr/local/bin/enscript -o - .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/enscript .... Modify [.filename]#/etc/printcap# to use the new filter: [.programlisting] .... :if=/usr/local/libexec/enscript:\ .... Test the filter by printing a plain text file. [[printing-lpd-filters-ps2pcl]] ==== Printing PostScript(R) to `PCL` Printers Many programs produce PostScript(R) documents. However, inexpensive printers often only understand plain text or `PCL`. This filter converts PostScript(R) files to `PCL` before sending them to the printer. Install the Ghostscript PostScript(R) interpreter, package:print/ghostscript9-base[], from the Ports Collection. Create [.filename]#/usr/local/libexec/ps2pcl# with these contents: [.programlisting] .... #!/bin/sh /usr/local/bin/gs -dSAFER -dNOPAUSE -dBATCH -q -sDEVICE=ljet4 -sOutputFile=- - .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/ps2pcl .... PostScript(R) input sent to this script will be rendered and converted to `PCL` before being sent on to the printer. Modify [.filename]#/etc/printcap# to use this new input filter: [.programlisting] .... :if=/usr/local/libexec/ps2pcl:\ .... Test the filter by sending a small PostScript(R) program to it: [source,shell] .... % printf "%%\!PS \n /Helvetica findfont 18 scalefont setfont \ 72 432 moveto (PostScript printing successful.) show showpage \004" | lpr .... [[printing-lpd-filters-smart]] ==== Smart Filters A filter that detects the type of input and automatically converts it to the correct format for the printer can be very convenient. The first two characters of a PostScript(R) file are usually `%!`. A filter can detect those two characters. PostScript(R) files can be sent on to a PostScript(R) printer unchanged. Text files can be converted to PostScript(R) with Enscript as shown earlier. Create [.filename]#/usr/local/libexec/psif# with these contents: [.programlisting] .... #!/bin/sh # # psif - Print PostScript or plain text on a PostScript printer # IFS="" read -r first_line first_two_chars=`expr "$first_line" : '\(..\)'` case "$first_two_chars" in %!) # %! : PostScript job, print it. echo "$first_line" && cat && exit 0 exit 2 ;; *) # otherwise, format with enscript ( echo "$first_line"; cat ) | /usr/local/bin/enscript -o - && exit 0 exit 2 ;; esac .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/psif .... Modify [.filename]#/etc/printcap# to use this new input filter: [.programlisting] .... :if=/usr/local/libexec/psif:\ .... Test the filter by printing PostScript(R) and plain text files. -[[printing-lpd-filters-othersmart]] -==== Other Smart Filters - -Writing a filter that detects many different types of input and formats them correctly is challenging. -package:print/apsfilter[] from the Ports Collection is a smart "magic" filter that detects dozens of file types and automatically converts them to the `PDL` understood by the printer. -See http://www.apsfilter.org[] for more details. - [[printing-lpd-queues]] === Multiple Queues The entries in [.filename]#/etc/printcap# are really definitions of _queues_. There can be more than one queue for a single printer. When combined with filters, multiple queues provide users more control over how their jobs are printed. As an example, consider a networked PostScript(R) laser printer in an office. Most users want to print plain text, but a few advanced users want to be able to print PostScript(R) files directly. Two entries can be created for the same printer in [.filename]#/etc/printcap#: [.programlisting] .... textprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/textprinter:\ :if=/usr/local/libexec/enscript:\ :lf=/var/log/lpd-errs: psprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/psprinter:\ :lf=/var/log/lpd-errs: .... Documents sent to `textprinter` will be formatted by the [.filename]#/usr/local/libexec/enscript# filter shown in an earlier example. Advanced users can print PostScript(R) files on `psprinter`, where no filtering is done. This multiple queue technique can be used to provide direct access to all kinds of printer features. A printer with a duplexer could use two queues, one for ordinary single-sided printing, and one with a filter that sends the command sequence to enable double-sided printing and then sends the incoming file. [[printing-lpd-monitor]] === Monitoring and Controlling Printing Several utilities are available to monitor print jobs and check and control printer operation. [[printing-lpd-monitor-lpq]] ==== man:lpq[1] man:lpq[1] shows the status of a user's print jobs. Print jobs from other users are not shown. Show the current user's pending jobs on a single printer: [source,shell] .... % lpq -Plp Rank Owner Job Files Total Size 1st jsmith 0 (standard input) 12792 bytes .... Show the current user's pending jobs on all printers: [source,shell] .... % lpq -a lp: Rank Owner Job Files Total Size 1st jsmith 1 (standard input) 27320 bytes laser: Rank Owner Job Files Total Size 1st jsmith 287 (standard input) 22443 bytes .... [[printing-lpd-monitor-lprm]] ==== man:lprm[1] man:lprm[1] is used to remove print jobs. Normal users are only allowed to remove their own jobs. `root` can remove any or all jobs. Remove all pending jobs from a printer: [source,shell] .... # lprm -Plp - dfA002smithy dequeued cfA002smithy dequeued dfA003smithy dequeued cfA003smithy dequeued dfA004smithy dequeued cfA004smithy dequeued .... Remove a single job from a printer. man:lpq[1] is used to find the job number. [source,shell] .... % lpq Rank Owner Job Files Total Size 1st jsmith 5 (standard input) 12188 bytes % lprm -Plp 5 dfA005smithy dequeued cfA005smithy dequeued .... [[printing-lpd-monitor-lpc]] ==== man:lpc[8] man:lpc[8] is used to check and modify printer status. `lpc` is followed by a command and an optional printer name. `all` can be used instead of a specific printer name, and the command will be applied to all printers. Normal users can view status with man:lpc[8]. Only `root` can use commands which modify printer status. Show the status of all printers: [source,shell] .... % lpc status all lp: queuing is enabled printing is enabled 1 entry in spool area printer idle laser: queuing is enabled printing is enabled 1 entry in spool area waiting for laser to come up .... Prevent a printer from accepting new jobs, then begin accepting new jobs again: [source,shell] .... # lpc disable lp lp: queuing disabled # lpc enable lp lp: queuing enabled .... Stop printing, but continue to accept new jobs. Then begin printing again: [source,shell] .... # lpc stop lp lp: printing disabled # lpc start lp lp: printing enabled daemon started .... Restart a printer after some error condition: [source,shell] .... # lpc restart lp lp: no daemon to abort printing enabled daemon restarted .... Turn the print queue off and disable printing, with a message to explain the problem to users: [source,shell] .... # lpc down lp Repair parts will arrive on Monday lp: printer and queuing disabled status message is now: Repair parts will arrive on Monday .... Re-enable a printer that is down: [source,shell] .... # lpc up lp lp: printing enabled daemon started .... See man:lpc[8] for more commands and options. [[printing-lpd-shared]] === Shared Printers Printers are often shared by multiple users in businesses and schools. Additional features are provided to make sharing printers more convenient. [[printing-shared-aliases]] ==== Aliases The printer name is set in the first line of the entry in [.filename]#/etc/printcap#. Additional names, or _aliases_, can be added after that name. Aliases are separated from the name and each other by vertical bars: [.programlisting] .... lp|repairsprinter|salesprinter:\ .... Aliases can be used in place of the printer name. For example, users in the Sales department print to their printer with [source,shell] .... % lpr -Psalesprinter sales-report.txt .... Users in the Repairs department print to _their_ printer with [source,shell] .... % lpr -Prepairsprinter repairs-report.txt .... All of the documents print on that single printer. When the Sales department grows enough to need their own printer, the alias can be removed from the shared printer entry and used as the name of a new printer. Users in both departments continue to use the same commands, but the Sales documents are sent to the new printer. [[printing-shared-headers]] ==== Header Pages It can be difficult for users to locate their documents in the stack of pages produced by a busy shared printer. _Header pages_ were created to solve this problem. A header page with the user name and document name is printed before each print job. These pages are also sometimes called _banner_ or _separator_ pages. Enabling header pages differs depending on whether the printer is connected directly to the computer with a `USB`, parallel, or serial cable, or is connected remotely over a network. Header pages on directly-connected printers are enabled by removing the `:sh:\` (Suppress Header) line from the entry in [.filename]#/etc/printcap#. These header pages only use line feed characters for new lines. Some printers will need the [.filename]#/usr/share/examples/printing/hpif# filter to prevent stairstepped text. The filter configures `PCL` printers to print both carriage returns and line feeds when a line feed is received. Header pages for network printers must be configured on the printer itself. Header page entries in [.filename]#/etc/printcap# are ignored. Settings are usually available from the printer front panel or a configuration web page accessible with a web browser. [[printing-lpd-references]] === References Example files: [.filename]#/usr/share/examples/printing/#. The _4.3BSD Line Printer Spooler Manual_, [.filename]#/usr/share/doc/smm/07.lpd/paper.ascii.gz#. Manual pages: man:printcap[5], man:lpd[8], man:lpr[1], man:lpc[8], man:lprm[1], man:lpq[1]. [[printing-other]] == Other Printing Systems Several other printing systems are available in addition to the built-in man:lpd[8]. These systems offer support for other protocols or additional features. [[printing-other-cups]] === CUPS (Common UNIX(R) Printing System) CUPS is a popular printing system available on many operating systems. Using CUPS on FreeBSD is documented in a separate article: extref:{cups}[CUPS] [[printing-other-hplip]] === HPLIP Hewlett Packard provides a printing system that supports many of their inkjet and laser printers. The port is package:print/hplip[]. The main web page is at https://developers.hp.com/hp-linux-imaging-and-printing[]. The port handles all the installation details on FreeBSD. Configuration information is shown at https://developers.hp.com/hp-linux-imaging-and-printing/install[]. [[printing-other-lprng]] === LPRng LPRng was developed as an enhanced alternative to man:lpd[8]. The port is package:sysutils/LPRng[]. For details and documentation, see http://www.lprng.com/[]. diff --git a/documentation/content/pl/books/handbook/printing/_index.adoc b/documentation/content/pl/books/handbook/printing/_index.adoc index 799bccc2de..ee1231df6f 100644 --- a/documentation/content/pl/books/handbook/printing/_index.adoc +++ b/documentation/content/pl/books/handbook/printing/_index.adoc @@ -1,773 +1,768 @@ --- title: Rozdział 9. Printing part: Część II. Codzienne czynności prev: books/handbook/kernelconfig next: books/handbook/linuxemu showBookMenu: true weight: 12 path: "/books/handbook/printing/" --- [[printing]] = Printing :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 9 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/printing/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] Putting information on paper is a vital function, despite many attempts to eliminate it. Printing has two basic components. The data must be delivered to the printer, and must be in a form that the printer can understand. [[printing-quick-start]] == Quick Start Basic printing can be set up quickly. The printer must be capable of printing plain `ASCII` text. For printing to other types of files, see <>. [.procedure] **** . Create a directory to store files while they are being printed: + [source,shell] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... + . As `root`, create [.filename]#/etc/printcap# with these contents: + [.programlisting] .... lp:\ :lp=/dev/unlpt0:\ <.> :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :lf=/var/log/lpd-errs: .... + <.> This line is for a printer connected to a `USB` port. + For a printer connected to a parallel or "printer" port, use: + [.programlisting] .... :lp=/dev/lpt0:\ .... + For a printer connected directly to a network, use: + [.programlisting] .... :lp=:rm=network-printer-name:rp=raw:\ .... + Replace _network-printer-name_ with the `DNS` host name of the network printer. + . Enable LPD by editing [.filename]#/etc/rc.conf#, adding this line: + [.programlisting] .... lpd_enable="YES" .... + Start the service: + [source,shell] .... # service lpd start Starting lpd. .... + . Print a test: + [source,shell] .... # printf "1. This printer can print.\n2. This is the second line.\n" | lpr .... + [TIP] ==== If both lines do not start at the left border, but "stairstep" instead, see <>. ==== + Text files can now be printed with `lpr`. Give the filename on the command line, or pipe output directly into `lpr`. + [source,shell] .... % lpr textfile.txt % ls -lh | lpr .... **** [[printing-connections]] == Printer Connections Printers are connected to computer systems in a variety of ways. Small desktop printers are usually connected directly to a computer's `USB` port. Older printers are connected to a parallel or "printer" port. Some printers are directly connected to a network, making it easy for multiple computers to share them. A few printers use a rare serial port connection. FreeBSD can communicate with all of these types of printers. [[printing-connections-usb]] `USB`:: `USB` printers can be connected to any available `USB` port on the computer. + When FreeBSD detects a `USB` printer, two device entries are created: [.filename]#/dev/ulpt0# and [.filename]#/dev/unlpt0#. Data sent to either device will be relayed to the printer. After each print job, [.filename]#ulpt0# resets the `USB` port. Resetting the port can cause problems with some printers, so the [.filename]#unlpt0# device is usually used instead. [.filename]#unlpt0# does not reset the USB port at all. [[printing-connections-parallel]] Parallel (`IEEE`-1284):: The parallel port device is [.filename]#/dev/lpt0#. This device appears whether a printer is attached or not, it is not autodetected. + Vendors have largely moved away from these "legacy" ports, and many computers no longer have them. Adapters can be used to connect a parallel printer to a `USB` port. With such an adapter, the printer can be treated as if it were actually a `USB` printer. Devices called _print servers_ can also be used to connect parallel printers directly to a network. [[printing-connections-serial]] Serial (RS-232):: Serial ports are another legacy port, rarely used for printers except in certain niche applications. Cables, connectors, and required wiring vary widely. + For serial ports built into a motherboard, the serial device name is [.filename]#/dev/cuau0# or [.filename]#/dev/cuau1#. Serial `USB` adapters can also be used, and these will appear as [.filename]#/dev/cuaU0#. + Several communication parameters must be known to communicate with a serial printer. The most important are _baud rate_ or `BPS` (Bits Per Second) and _parity_. Values vary, but typical serial printers use a baud rate of 9600 and no parity. [[printing-connections-network]] Network:: Network printers are connected directly to the local computer network. + The `DNS` hostname of the printer must be known. If the printer is assigned a dynamic address by `DHCP`, `DNS` should be dynamically updated so that the host name always has the correct `IP` address. Network printers are often given static `IP` addresses to avoid this problem. + Most network printers understand print jobs sent with the LPD protocol. A print queue name can also be specified. Some printers process data differently depending on which queue is used. For example, a `raw` queue prints the data unchanged, while the `text` queue adds carriage returns to plain text. + Many network printers can also print data sent directly to port 9100. [[printing-connections-summary]] === Summary Wired network connections are usually the easiest to set up and give the fastest printing. For direct connection to the computer, `USB` is preferred for speed and simplicity. Parallel connections work but have limitations on cable length and speed. Serial connections are more difficult to configure. Cable wiring differs between models, and communication parameters like baud rate and parity bits must add to the complexity. Fortunately, serial printers are rare. [[printing-pdls]] == Common Page Description Languages Data sent to a printer must be in a language that the printer can understand. These languages are called Page Description Languages, or PDLs. [[print-pdls-ascii]] `ASCII`:: Plain `ASCII` text is the simplest way to send data to a printer. Characters correspond one to one with what will be printed: an `A` in the data prints an `A` on the page. Very little formatting is available. There is no way to select a font or proportional spacing. The forced simplicity of plain `ASCII` means that text can be printed straight from the computer with little or no encoding or translation. The printed output corresponds directly with what was sent. + Some inexpensive printers cannot print plain `ASCII` text. This makes them more difficult to set up, but it is usually still possible. [[print-pdls-postscript]] PostScript(R):: PostScript(R) is almost the opposite of `ASCII`. Rather than simple text, a PostScript(R) program is a set of instructions that draw the final document. Different fonts and graphics can be used. However, this power comes at a price. The program that draws the page must be written. Usually this program is generated by application software, so the process is invisible to the user. + Inexpensive printers sometimes leave out PostScript(R) compatibility as a cost-saving measure. [[print-pdls-pcl]] `PCL` (Printer Command Language):: `PCL` is an extension of `ASCII`, adding escape sequences for formatting, font selection, and printing graphics. Many printers provide `PCL5` support. Some support the newer `PCL6` or `PCLXL`. These later versions are supersets of `PCL5` and can provide faster printing. [[print-pdls-host-based]] Host-Based:: Manufacturers can reduce the cost of a printer by giving it a simple processor and very little memory. These printers are not capable of printing plain text. Instead, bitmaps of text and graphics are drawn by a driver on the host computer and then sent to the printer. These are called _host-based_ printers. + Communication between the driver and a host-based printer is often through proprietary or undocumented protocols, making them functional only on the most common operating systems. [[print-pdls-table]] === Converting PostScript(R) to Other PDLs Many applications from the Ports Collection and FreeBSD utilities produce PostScript(R) output. This table shows the utilities available to convert that into other common PDLs: [[print-pdls-ps-to-other-tbl]] .Output PDLs [cols="1,1,1", frame="none", options="header"] |=== <| Output PDL <| Generated By <| Notes |`PCL` or `PCL5` |package:print/ghostscript9-base[] |`-sDEVICE=ljet4` for monochrome, `-sDEVICE=cljet5` for color |`PCLXL` or `PCL6` |package:print/ghostscript9-base[] |`-sDEVICE=pxlmono` for monochrome, `-sDEVICE=pxlcolor` for color |`ESC/P2` |package:print/ghostscript9-base[] |`-sDEVICE=uniprint` |`XQX` |package:print/foo2zjs[] | |=== [[print-pdls-summary]] === Summary For the easiest printing, choose a printer that supports PostScript(R). Printers that support `PCL` are the next preferred. With package:print/ghostscript9-base[], these printers can be used as if they understood PostScript(R) natively. Printers that support PostScript(R) or `PCL` directly almost always support direct printing of plain `ASCII` text files also. Line-based printers like typical inkjets usually do not support PostScript(R) or `PCL`. They often can print plain `ASCII` text files. package:print/ghostscript9-base[] supports the PDLs used by some of these printers. However, printing an entire graphic-based page on these printers is often very slow due to the large amount of data to be transferred and printed. Host-based printers are often more difficult to set up. Some cannot be used at all because of proprietary PDLs. Avoid these printers when possible. Descriptions of many PDLs can be found at http://www.undocprint.org/formats/page_description_languages[]. The particular `PDL` used by various models of printers can be found at http://www.openprinting.org/printers[]. [[printing-direct]] == Direct Printing For occasional printing, files can be sent directly to a printer device without any setup. For example, a file called [.filename]#sample.txt# can be sent to a `USB` printer: [source,shell] .... # cp sample.txt /dev/unlpt0 .... Direct printing to network printers depends on the abilities of the printer, but most accept print jobs on port 9100, and man:nc[1] can be used with them. To print the same file to a printer with the `DNS` hostname of _netlaser_: [source,shell] .... # nc netlaser 9100 < sample.txt .... [[printing-lpd]] == LPD (Line Printer Daemon) Printing a file in the background is called _spooling_. A spooler allows the user to continue with other programs on the computer without waiting for the printer to slowly complete the print job. FreeBSD includes a spooler called man:lpd[8]. Print jobs are submitted with man:lpr[1]. [[printing-lpd-setup]] === Initial Setup A directory for storing print jobs is created, ownership is set, and the permissions are set to prevent other users from viewing the contents of those files: [source,shell] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... Printers are defined in [.filename]#/etc/printcap#. An entry for each printer includes details like a name, the port where it is attached, and various other settings. Create [.filename]#/etc/printcap# with these contents: [.programlisting] .... lp:\ <.> :lp=/dev/unlpt0:\ <.> :sh:\ <.> :mx#0:\ <.> :sd=/var/spool/lpd/lp:\ <.> :lf=/var/log/lpd-errs: <.> .... <.> The name of this printer. man:lpr[1] sends print jobs to the `lp` printer unless another printer is specified with `-P`, so the default printer should be named `lp`. <.> The device where the printer is connected. Replace this line with the appropriate one for the connection type shown here. <.> Suppress the printing of a header page at the start of a print job. <.> Do not limit the maximum size of a print job. <.> The path to the spooling directory for this printer. Each printer uses its own spooling directory. <.> The log file where errors on this printer will be reported. After creating [.filename]#/etc/printcap#, use man:chkprintcap[8] to test it for errors: [source,shell] .... # chkprintcap .... Fix any reported problems before continuing. Enable man:lpd[8] in [.filename]#/etc/rc.conf#: [.programlisting] .... lpd_enable="YES" .... Start the service: [source,shell] .... # service lpd start .... [[printing-lpd-lpr]] === Printing with man:lpr[1] Documents are sent to the printer with `lpr`. A file to be printed can be named on the command line or piped into `lpr`. These two commands are equivalent, sending the contents of [.filename]#doc.txt# to the default printer: [source,shell] .... % lpr doc.txt % cat doc.txt | lpr .... Printers can be selected with `-P`. To print to a printer called _laser_: [source,shell] .... % lpr -Plaser doc.txt .... [[printing-lpd-filters]] === Filters The examples shown so far have sent the contents of a text file directly to the printer. As long as the printer understands the content of those files, output will be printed correctly. Some printers are not capable of printing plain text, and the input file might not even be plain text. _Filters_ allow files to be translated or processed. The typical use is to translate one type of input, like plain text, into a form that the printer can understand, like PostScript(R) or `PCL`. Filters can also be used to provide additional features, like adding page numbers or highlighting source code to make it easier to read. The filters discussed here are _input filters_ or _text filters_. These filters convert the incoming file into different forms. Use man:su[1] to become `root` before creating the files. Filters are specified in [.filename]#/etc/printcap# with the `if=` identifier. To use [.filename]#/usr/local/libexec/lf2crlf# as a filter, modify [.filename]#/etc/printcap# like this: [.programlisting] .... lp:\ :lp=/dev/unlpt0:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :if=/usr/local/libexec/lf2crlf:\ <.> :lf=/var/log/lpd-errs: .... <.> `if=` identifies the _input filter_ that will be used on incoming text. [TIP] ==== The backslash _line continuation_ characters at the end of the lines in [.filename]#printcap# entries reveal that an entry for a printer is really just one long line with entries delimited by colon characters. An earlier example can be rewritten as a single less-readable line: [.programlisting] .... lp:lp=/dev/unlpt0:sh:mx#0:sd=/var/spool/lpd/lp:if=/usr/local/libexec/lf2crlf:lf=/var/log/lpd-errs: .... ==== [[printing-lpd-filters-stairstep]] ==== Preventing Stairstepping on Plain Text Printers Typical FreeBSD text files contain only a single line feed character at the end of each line. These lines will "stairstep" on a standard printer: [.programlisting] .... A printed file looks like the steps of a staircase scattered by the wind .... A filter can convert the newline characters into carriage returns and newlines. The carriage returns make the printer return to the left after each line. Create [.filename]#/usr/local/libexec/lf2crlf# with these contents: [.programlisting] .... #!/bin/sh CR=$'\r' /usr/bin/sed -e "s/$/${CR}/g" .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/lf2crlf .... Modify [.filename]#/etc/printcap# to use the new filter: [.programlisting] .... :if=/usr/local/libexec/lf2crlf:\ .... Test the filter by printing the same plain text file. The carriage returns will cause each line to start at the left side of the page. [[printing-lpd-filters-enscript]] ==== Fancy Plain Text on PostScript(R) Printers with package:print/enscript[] GNUEnscript converts plain text files into nicely-formatted PostScript(R) for printing on PostScript(R) printers. It adds page numbers, wraps long lines, and provides numerous other features to make printed text files easier to read. Depending on the local paper size, install either package:print/enscript-letter[] or package:print/enscript-a4[] from the Ports Collection. Create [.filename]#/usr/local/libexec/enscript# with these contents: [.programlisting] .... #!/bin/sh /usr/local/bin/enscript -o - .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/enscript .... Modify [.filename]#/etc/printcap# to use the new filter: [.programlisting] .... :if=/usr/local/libexec/enscript:\ .... Test the filter by printing a plain text file. [[printing-lpd-filters-ps2pcl]] ==== Printing PostScript(R) to `PCL` Printers Many programs produce PostScript(R) documents. However, inexpensive printers often only understand plain text or `PCL`. This filter converts PostScript(R) files to `PCL` before sending them to the printer. Install the Ghostscript PostScript(R) interpreter, package:print/ghostscript9-base[], from the Ports Collection. Create [.filename]#/usr/local/libexec/ps2pcl# with these contents: [.programlisting] .... #!/bin/sh /usr/local/bin/gs -dSAFER -dNOPAUSE -dBATCH -q -sDEVICE=ljet4 -sOutputFile=- - .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/ps2pcl .... PostScript(R) input sent to this script will be rendered and converted to `PCL` before being sent on to the printer. Modify [.filename]#/etc/printcap# to use this new input filter: [.programlisting] .... :if=/usr/local/libexec/ps2pcl:\ .... Test the filter by sending a small PostScript(R) program to it: [source,shell] .... % printf "%%\!PS \n /Helvetica findfont 18 scalefont setfont \ 72 432 moveto (PostScript printing successful.) show showpage \004" | lpr .... [[printing-lpd-filters-smart]] ==== Smart Filters A filter that detects the type of input and automatically converts it to the correct format for the printer can be very convenient. The first two characters of a PostScript(R) file are usually `%!`. A filter can detect those two characters. PostScript(R) files can be sent on to a PostScript(R) printer unchanged. Text files can be converted to PostScript(R) with Enscript as shown earlier. Create [.filename]#/usr/local/libexec/psif# with these contents: [.programlisting] .... #!/bin/sh # # psif - Print PostScript or plain text on a PostScript printer # IFS="" read -r first_line first_two_chars=`expr "$first_line" : '\(..\)'` case "$first_two_chars" in %!) # %! : PostScript job, print it. echo "$first_line" && cat && exit 0 exit 2 ;; *) # otherwise, format with enscript ( echo "$first_line"; cat ) | /usr/local/bin/enscript -o - && exit 0 exit 2 ;; esac .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/psif .... Modify [.filename]#/etc/printcap# to use this new input filter: [.programlisting] .... :if=/usr/local/libexec/psif:\ .... Test the filter by printing PostScript(R) and plain text files. -[[printing-lpd-filters-othersmart]] -==== Other Smart Filters - -Writing a filter that detects many different types of input and formats them correctly is challenging. package:print/apsfilter[] from the Ports Collection is a smart "magic" filter that detects dozens of file types and automatically converts them to the `PDL` understood by the printer. See http://www.apsfilter.org[] for more details. - [[printing-lpd-queues]] === Multiple Queues The entries in [.filename]#/etc/printcap# are really definitions of _queues_. There can be more than one queue for a single printer. When combined with filters, multiple queues provide users more control over how their jobs are printed. As an example, consider a networked PostScript(R) laser printer in an office. Most users want to print plain text, but a few advanced users want to be able to print PostScript(R) files directly. Two entries can be created for the same printer in [.filename]#/etc/printcap#: [.programlisting] .... textprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/textprinter:\ :if=/usr/local/libexec/enscript:\ :lf=/var/log/lpd-errs: psprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/psprinter:\ :lf=/var/log/lpd-errs: .... Documents sent to `textprinter` will be formatted by the [.filename]#/usr/local/libexec/enscript# filter shown in an earlier example. Advanced users can print PostScript(R) files on `psprinter`, where no filtering is done. This multiple queue technique can be used to provide direct access to all kinds of printer features. A printer with a duplexer could use two queues, one for ordinary single-sided printing, and one with a filter that sends the command sequence to enable double-sided printing and then sends the incoming file. [[printing-lpd-monitor]] === Monitoring and Controlling Printing Several utilities are available to monitor print jobs and check and control printer operation. [[printing-lpd-monitor-lpq]] ==== man:lpq[1] man:lpq[1] shows the status of a user's print jobs. Print jobs from other users are not shown. Show the current user's pending jobs on a single printer: [source,shell] .... % lpq -Plp Rank Owner Job Files Total Size 1st jsmith 0 (standard input) 12792 bytes .... Show the current user's pending jobs on all printers: [source,shell] .... % lpq -a lp: Rank Owner Job Files Total Size 1st jsmith 1 (standard input) 27320 bytes laser: Rank Owner Job Files Total Size 1st jsmith 287 (standard input) 22443 bytes .... [[printing-lpd-monitor-lprm]] ==== man:lprm[1] man:lprm[1] is used to remove print jobs. Normal users are only allowed to remove their own jobs. `root` can remove any or all jobs. Remove all pending jobs from a printer: [source,shell] .... # lprm -Plp - dfA002smithy dequeued cfA002smithy dequeued dfA003smithy dequeued cfA003smithy dequeued dfA004smithy dequeued cfA004smithy dequeued .... Remove a single job from a printer. man:lpq[1] is used to find the job number. [source,shell] .... % lpq Rank Owner Job Files Total Size 1st jsmith 5 (standard input) 12188 bytes % lprm -Plp 5 dfA005smithy dequeued cfA005smithy dequeued .... [[printing-lpd-monitor-lpc]] ==== man:lpc[8] man:lpc[8] is used to check and modify printer status. `lpc` is followed by a command and an optional printer name. `all` can be used instead of a specific printer name, and the command will be applied to all printers. Normal users can view status with man:lpc[8]. Only `root` can use commands which modify printer status. Show the status of all printers: [source,shell] .... % lpc status all lp: queuing is enabled printing is enabled 1 entry in spool area printer idle laser: queuing is enabled printing is enabled 1 entry in spool area waiting for laser to come up .... Prevent a printer from accepting new jobs, then begin accepting new jobs again: [source,shell] .... # lpc disable lp lp: queuing disabled # lpc enable lp lp: queuing enabled .... Stop printing, but continue to accept new jobs. Then begin printing again: [source,shell] .... # lpc stop lp lp: printing disabled # lpc start lp lp: printing enabled daemon started .... Restart a printer after some error condition: [source,shell] .... # lpc restart lp lp: no daemon to abort printing enabled daemon restarted .... Turn the print queue off and disable printing, with a message to explain the problem to users: [source,shell] .... # lpc down lp Repair parts will arrive on Monday lp: printer and queuing disabled status message is now: Repair parts will arrive on Monday .... Re-enable a printer that is down: [source,shell] .... # lpc up lp lp: printing enabled daemon started .... See man:lpc[8] for more commands and options. [[printing-lpd-shared]] === Shared Printers Printers are often shared by multiple users in businesses and schools. Additional features are provided to make sharing printers more convenient. [[printing-shared-aliases]] ==== Aliases The printer name is set in the first line of the entry in [.filename]#/etc/printcap#. Additional names, or _aliases_, can be added after that name. Aliases are separated from the name and each other by vertical bars: [.programlisting] .... lp|repairsprinter|salesprinter:\ .... Aliases can be used in place of the printer name. For example, users in the Sales department print to their printer with [source,shell] .... % lpr -Psalesprinter sales-report.txt .... Users in the Repairs department print to _their_ printer with [source,shell] .... % lpr -Prepairsprinter repairs-report.txt .... All of the documents print on that single printer. When the Sales department grows enough to need their own printer, the alias can be removed from the shared printer entry and used as the name of a new printer. Users in both departments continue to use the same commands, but the Sales documents are sent to the new printer. [[printing-shared-headers]] ==== Header Pages It can be difficult for users to locate their documents in the stack of pages produced by a busy shared printer. _Header pages_ were created to solve this problem. A header page with the user name and document name is printed before each print job. These pages are also sometimes called _banner_ or _separator_ pages. Enabling header pages differs depending on whether the printer is connected directly to the computer with a `USB`, parallel, or serial cable, or is connected remotely over a network. Header pages on directly-connected printers are enabled by removing the `:sh:\` (Suppress Header) line from the entry in [.filename]#/etc/printcap#. These header pages only use line feed characters for new lines. Some printers will need the [.filename]#/usr/shared/examples/printing/hpif# filter to prevent stairstepped text. The filter configures `PCL` printers to print both carriage returns and line feeds when a line feed is received. Header pages for network printers must be configured on the printer itself. Header page entries in [.filename]#/etc/printcap# are ignored. Settings are usually available from the printer front panel or a configuration web page accessible with a web browser. [[printing-lpd-references]] === References Example files: [.filename]#/usr/shared/examples/printing/#. The _4.3BSD Line Printer Spooler Manual_, [.filename]#/usr/shared/doc/smm/07.lpd/paper.ascii.gz#. Manual pages: man:printcap[5], man:lpd[8], man:lpr[1], man:lpc[8], man:lprm[1], man:lpq[1]. [[printing-other]] == Other Printing Systems Several other printing systems are available in addition to the built-in man:lpd[8]. These systems offer support for other protocols or additional features. [[printing-other-cups]] === CUPS (Common UNIX(R) Printing System) CUPS is a popular printing system available on many operating systems. Using CUPS on FreeBSD is documented in a separate article: extref:{cups}[CUPS] [[printing-other-hplip]] === HPLIP Hewlett Packard provides a printing system that supports many of their inkjet and laser printers. The port is package:print/hplip[]. The main web page is at http://hplipopensource.com/hplip-web/index.html[]. The port handles all the installation details on FreeBSD. Configuration information is shown at http://hplipopensource.com/hplip-web/install/manual/hp_setup.html[]. [[printing-other-lprng]] === LPRng LPRng was developed as an enhanced alternative to man:lpd[8]. The port is package:sysutils/LPRng[]. For details and documentation, see http://www.lprng.com/[]. diff --git a/documentation/content/pt-br/books/handbook/printing/_index.adoc b/documentation/content/pt-br/books/handbook/printing/_index.adoc index 415eda5edf..1bfd467d6d 100644 --- a/documentation/content/pt-br/books/handbook/printing/_index.adoc +++ b/documentation/content/pt-br/books/handbook/printing/_index.adoc @@ -1,755 +1,750 @@ --- title: Capítulo 9. Impressão part: Parte II. Tarefas comuns prev: books/handbook/kernelconfig next: books/handbook/linuxemu showBookMenu: true weight: 12 path: "/books/handbook/printing/" --- [[printing]] = Impressão :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 9 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/printing/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] Colocar informações no papel é uma função vital, apesar de muitas tentativas de eliminá-la. A impressão tem dois componentes básicos. Os dados devem ser entregues à impressora e devem estar em um formato que a impressora possa entender. [[printing-quick-start]] == Inicio Rápido A impressão básica pode ser configurada rapidamente. A impressora deve ser capaz de imprimir texto simples ASCII. Para imprimir em outros tipos de arquivos, consulte <>. [.procedure] ==== . Crie um diretório para armazenar arquivos enquanto eles estão sendo impressos: + [source,shell] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... + . Como `root`, crie [.filename]#/etc/printcap# com estes conteúdos: + [.programlisting] .... lp:\ :lp=/dev/unlpt0:\ <.> :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :lf=/var/log/lpd-errs: .... + <.> Esta linha é para uma impressora conectada a uma porta USB.Para uma impressora conectada a uma porta paralela ou uma porta de "impressora", use:Para uma impressora conectada diretamente a uma rede, use:Substitua _network-printer-name_ pelo nome de host DNS da impressora de rede. . Ative o `lpd` editando o [.filename]#/etc/rc.conf#, adicionando esta linha: + [.programlisting] .... lpd_enable="YES" .... + Inicie o serviço: + [source,shell] .... # service lpd start Starting lpd. .... + . Imprima um teste: + [source,shell] .... # printf "1. This printer can print.\n2. This is the second line.\n" | lpr .... + [TIP] ====== Se ambas as linhas não iniciarem na borda esquerda, mas em "degrau", consulte <>. ====== + Arquivos de texto agora podem ser impressos com `lpr`. Dê o nome do arquivo na linha de comando ou canalize a saída diretamente no `lpr`. + [source,shell] .... % lpr textfile.txt % ls -lh | lpr .... ==== [[printing-connections]] == Conexões de Impressora As impressoras são conectadas a sistemas de computadores de várias maneiras. Geralmente, as impressoras desktop pequenas são conectadas diretamente à porta USB do computador. As impressoras mais antigas são conectadas a uma porta paralela ou a porta de "impressora". Algumas impressoras estão diretamente conectadas a uma rede, facilitando o compartilhamento com vários computadores. Algumas impressoras usam uma rara conexão de porta serial. O FreeBSD pode se comunicar com todos esses tipos de impressoras. [[printing-connections-usb]] USB:: As impressoras USB podem ser conectadas a qualquer porta USB disponível no computador. + Quando o FreeBSD detecta uma impressora USB, duas entradas de dispositivos são criadas: [.filename]#/dev/ulpt0# e [.filename]#/dev/unlpt0#. Os dados enviados para qualquer dispositivo serão retransmitidos para a impressora. Após cada trabalho de impressão, o [.filename]#ulpt0# reseta a porta USB. O reset da porta pode causar problemas em algumas impressoras, portanto, o dispositivo [.filename]#unlpt0# é normalmente usado em seu lugar. O [.filename]#unlpt0# não reseta a porta USB. [[printing-connections-parallel]] Paralela (IEEE-1284):: O dispositivo da porta paralela é o [.filename]#/dev/lpt0#. Este dispositivo aparece independentemente se uma impressora está ou não conectada, ela não é autodetectada. + A maior parte dos fabricantes se afastou destas portas "legadas" e muitos computadores não as têm mais. Adaptadores podem ser usados para conectar uma impressora paralela a uma porta USB. Com este tipo de adaptador, a impressora pode ser tratada como se fosse uma impressora USB. Dispositivos chamados _servidores de impressão_ também podem ser usados para conectar impressoras paralelas diretamente a uma rede. [[printing-connections-serial]] Serial (RS-232):: Portas seriais são outro tipo de porta legada, raramente usada para impressoras, exceto em determinadas aplicações de nicho. Os cabos, os conectores e a fiação necessária variam muito. + Para portas seriais incorporadas em uma placa-mãe, o nome do dispositivo serial é [.filename]#/dev/cuau0# ou [.filename]#/dev/cuau1#. Os adaptadores Seriais USB também podem ser usados, e eles aparecerão como [.filename]#/dev/cuaU0#. + Vários parâmetros de comunicação devem ser conhecidos para se comunicar com uma impressora serial. Os mais importantes são _baud rate_ ou BPS (Bits por segundo) e _paridade_. Os valores variam, mas as impressoras seriais típicas usam uma taxa de transmissão de 9600 e nenhuma paridade. [[printing-connections-network]] Rede:: As impressoras de rede estão conectadas diretamente à rede de computadores local. + O nome de host DNS da impressora deve ser conhecido. Se a impressora tiver um endereço dinâmico atribuído por DHCP, o DNS deverá ser atualizado dinamicamente para que o nome do host tenha sempre o endereço IP correto. As impressoras de rede geralmente recebem endereços IP estáticos para evitar esse problema. + A maioria das impressoras de rede entende os trabalhos de impressão enviados com o protocolo LPD. Um nome de fila de impressão também pode ser especificado. Algumas impressoras processam dados de maneira diferente, dependendo de qual fila é usada. Por exemplo, uma fila `raw` imprime os dados inalterados, enquanto a fila `text` adiciona retornos de carro aos textos simples. + Muitas impressoras de rede também podem imprimir dados enviados diretamente para a porta 9100. [[printing-connections-summary]] === Resumo As conexões de rede com fio geralmente são as mais fáceis de configurar e oferecem a impressão mais rápida. Para conexão direta com o computador, a conexão USB é preferida em função da velocidade e da simplicidade. As conexões paralelas funcionam, mas têm limitações no comprimento do cabo e na velocidade. Conexões seriais são mais difíceis de configurar. A configuração do cabo difere entre os modelos, e os parâmetros de comunicação, como taxa de transmissão e bits de paridade, se somam a complexidade. Felizmente, as impressoras seriais são raras. [[printing-pdls]] == Linguagens de Descrição de Página Comuns Os dados enviados a uma impressora devem estar em um idioma que a impressora possa entender. Esses idiomas são chamados de Linguagens de Descrição de Página ou PDLs. [[print-pdls-ascii]] ASCII:: Texto ASCII simples é a maneira mais simples de enviar dados para uma impressora. Os caracteres correspondem um a um com o que será impresso: um `A` nos dados imprime um `A` na página. Muito pouca formatação está disponível. Não há como selecionar uma fonte ou espaçamento proporcional. A simplicidade forçada do texto ASCII simples significa que o texto pode ser impresso diretamente do computador com pouca ou nenhuma codificação ou tradução. A saída impressa corresponde diretamente ao que foi enviado. + Algumas impressoras baratas não conseguem imprimir texto ASCII simples. Isso as torna mais difíceis de configurar, mas geralmente ainda é possível fazê-lo. [[print-pdls-postscript]] PostScript(TM):: O PostScript(TM) é quase o oposto do ASCII. Em vez de um texto simples, um programa PostScript(TM) é um conjunto de instruções que desenham o documento final. Fontes e gráficos diferentes podem ser usados. No entanto, esse poder tem um preço. O programa que desenha a página deve ser escrito. Geralmente este programa é gerado pelo software aplicativo, portanto, o processo é invisível para o usuário. + Impressoras baratas às vezes deixam de fora a compatibilidade com o PostScript(TM) como uma medida para economia de custos. [[print-pdls-pcl]] PCL (linguagem de comando de impressora):: A PCL é uma extensão do ASCII, adicionando sequências de escape para formatação, seleção de fontes e impressão de gráficos. Muitas impressoras fornecem suporte para PCL5. Algumas suportam o mais recente PCL6 ou o PCLXL. Essas versões posteriores são superconjuntos do PCL5 e podem fornecer uma impressão mais rápida. [[print-pdls-host-based]] Baseado em Host:: Os fabricantes podem reduzir o custo de uma impressora, oferecendo um processador simples e muito pouca memória. Essas impressoras não são capazes de imprimir texto simples. Em vez disso, bitmaps de texto e gráficos são desenhados por um driver no computador host e, em seguida, enviados para a impressora. Estas são chamadas de impressoras _baseadas em host_. + A comunicação entre o driver e uma impressora baseada em host geralmente ocorre por meio de protocolos proprietários ou não documentados, tornando-os funcionais apenas nos sistemas operacionais mais comuns. [[print-pdls-table]] === Convertendo PostScript(TM) para outros PDLs Muitas aplicações da Coleção de Ports e muitos utilitários do FreeBSD produzem uma saída em PostScript(TM). Esta tabela mostra os utilitários disponíveis para converter o postscript em outros PDLs comuns: [[print-pdls-ps-to-other-tbl]] .Saída PDLs [cols="1,1,1", frame="none", options="header"] |=== <| Saída PDL <| Gerado por <| Notas |PCL ou PCL5 |package:print/ghostscript9[] |`-sDEVICE=ljet4` para monocromático, e `-sDEVICE=cljet5` para colorido |PCLXL ou PCL6 |package:print/ghostscript9[] |`-sDEVICE=pxlmono` para monocromático, `-sDEVICE=pxlcolor` para colorido |ESC/P2 |package:print/ghostscript9[] |`-sDEVICE=uniprint` |XQX |package:print/foo2zjs[] | |=== [[print-pdls-summary]] === Resumo Para facilitar a impressão, escolha uma impressora que suporte PostScript(TM). Impressoras que suportam PCL são as próximas preferidas. Com o package:print/ghostscript[], essas impressoras podem ser usadas como se entendessem nativamente PostScript(TM). Impressoras que suportam PostScript(TM) ou PCL diretamente quase sempre suportam a impressão direta de arquivos de texto simples ASCII também. Impressoras baseadas em linha, como as jatos de tinta comuns, geralmente não suportam PostScript(TM) ou PCL. Elas geralmente podem imprimir arquivos de texto plano ASCII. O package:print/ghostscript[] suporta os PDL usados por algumas dessas impressoras. Entretanto, a impressão de uma página inteira baseada em gráficos nessas impressoras costuma ser muito lenta devido à grande quantidade de dados a serem transferidos e impressos. Geralmente, as impressoras baseadas em host são mais difíceis de configurar. Algumas não podem ser usadas por causa de PDLs proprietários. Evite essas impressoras quando possível. Descrições de muitos PDLs podem ser encontradas em http://www.undocprint.org/formats/page_description_languages[]. O PDL específico usado por vários modelos de impressoras pode ser encontrado em http://www.openprinting.org/printers[]. [[printing-direct]] == Impressão Direta Para impressão ocasional, os arquivos podem ser enviados diretamente para um dispositivo de impressora sem qualquer configuração. Por exemplo, um arquivo chamado [.filename]#exemplo.txt# pode ser enviado para uma impressora USB: [source,shell] .... # cp sample.txt /dev/unlpt0 .... A impressão direta para impressoras de rede depende das capacidades da impressora, mas a maioria aceita trabalhos de impressão na porta 9100, e o man:nc[1] pode ser usado com eles. Para imprimir o mesmo arquivo em uma impressora com o nome de host DNS de _netlaser_: [source,shell] .... # nc netlaser 9100 < sample.txt .... [[printing-lpd]] == LPD (Daemon de impressora de linha) A impressão de um arquivo em segundo plano é chamada de _spooling_. Um spooler permite que o usuário continue com outros programas no computador sem ter de esperar que a impressora conclua lentamente o trabalho de impressão. O FreeBSD inclui um spooler chamado man:lpd[8]. Os trabalhos de impressão são enviados com o comando man:lpr[1]. [[printing-lpd-setup]] === Configuração inicial Um diretório para armazenar trabalhos de impressão é criado, a propriedade é definida e as permissões são definidas para impedir que outros usuários visualizem o conteúdo desses arquivos: [source,shell] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... As impressoras são definidas no [.filename]#/etc/printcap#. Uma entrada para cada impressora inclui detalhes como um nome, a porta onde ela está conectada e várias outras configurações. Crie [.filename]#/etc/printcap# com estes conteúdos: [.programlisting] .... lp:\ <.> :lp=/dev/unlpt0:\ <.> :sh:\ <.> :mx#0:\ <.> :sd=/var/spool/lpd/lp:\ <.> :lf=/var/log/lpd-errs: <.> .... <.> O nome desta impressora. O man:lpr[1] envia trabalhos de impressão para a impressora `lp`, a menos que outra impressora seja especificada com `-P`, portanto, a impressora padrão deve ser denominada `lp`. <.> O dispositivo em que a impressora está conectada. Substitua esta linha pela apropriada para o tipo de conexão mostrado aqui. <.> Suprimir a impressão de uma página de cabeçalho no início de um trabalho de impressão. <.> Não limite o tamanho máximo de um trabalho de impressão. <.> O caminho para o diretório de spooling desta impressora. Cada impressora usa seu próprio diretório de spooling. <.> O arquivo de log no qual os erros nesta impressora serão relatados. Depois de criar o [.filename]#/etc/printcap#, use man:chkprintcap[8] para testar se há erros: [source,shell] .... # chkprintcap .... Corrija quaisquer problemas relatados antes de continuar. Ative o man:lpd[8] no [.filename]#/etc/rc.conf#: [.programlisting] .... lpd_enable="YES" .... Inicie o serviço: [source,shell] .... # service lpd start .... [[printing-lpd-lpr]] === Imprimindo com o man:lpr[1] Os documentos são enviados para a impressora com o `lpr`. Um arquivo a ser impresso pode ser nomeado na linha de comando ou canalizado para o `lpr`. Esses dois comandos são equivalentes, enviando o conteúdo de [.filename]#doc.txt# para a impressora padrão: [source,shell] .... % lpr doc.txt % cat doc.txt | lpr .... Impressoras podem ser selecionadas com `-P`. Para imprimir em uma impressora chamada _laser_: [source,shell] .... % lpr -Plaser doc.txt .... [[printing-lpd-filters]] === Filtros Os exemplos mostrados até agora enviaram o conteúdo de um arquivo de texto diretamente para a impressora. Contanto que a impressora entenda o conteúdo desses arquivos, a saída será impressa corretamente. Algumas impressoras não são capazes de imprimir texto simples, e o arquivo de entrada pode nem ser texto simples. _Filtros_ permitem que os arquivos sejam traduzidos ou processados. O uso típico é traduzir um tipo de entrada, como texto simples, em um formato que a impressora possa entender, como PostScript(TM) ou PCL. Os filtros também podem ser usados para fornecer recursos adicionais, como adicionar números de página ou destacar o código-fonte para facilitar a leitura. Os filtros discutidos aqui são _filtros de entrada_ ou _filtros de texto_. Esses filtros convertem o arquivo recebido em diferentes formatos. Use man:su[1] para se tornar `root` antes de criar os arquivos. Os filtros são especificados em [.filename]#/etc/printcap# com o identificador `if=`. Para usar [.filename]#/usr/local/libexec/lf2crlf# como um filtro, modifique o [.filename]#/etc/printcap# assim: [.programlisting] .... lp:\ :lp=/dev/unlpt0:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :if=/usr/local/libexec/lf2crlf:\ <.> :lf=/var/log/lpd-errs: .... <.> `if=` identifica o _filtro de entrada_ que será usado no texto recebido. [TIP] ==== Os caracteres backslash de _continuação de linha_ no final das linhas nas entradas do [.filename]#printcap# revelam que uma entrada para uma impressora é na verdade apenas uma linha longa com entradas delimitadas por dois pontos. O exemplo anterior pode ser reescrito como uma única linha menos legível: [.programlisting] .... lp:lp=/dev/unlpt0:sh:mx#0:sd=/var/spool/lpd/lp:if=/usr/local/libexec/lf2crlf:lf=/var/log/lpd-errs: .... ==== [[printing-lpd-filters-stairstep]] ==== Impedindo degraus em impressoras de texto simples Os arquivos de texto típicos do FreeBSD contêm apenas um único caractere de feed de linha no final de cada linha. Estas linhas vão ficar em "degraus" em uma impressora padrão: [.programlisting] .... Um arquivo impresso parece                     como os degraus de uma escada                                               espalhados pelo vento .... Um filtro pode converter os caracteres de nova linha em retornos de carro e novas linhas. Os retornos de carro fazem a impressora retornar para a esquerda após cada linha. Crie o [.filename]#/usr/local/libexec/lf2crlf# com este conteúdo: [.programlisting] .... #!/bin/sh CR=$'\r' /usr/bin/sed -e "s/$/${CR}/g" .... Defina as permissões e torne-o executável: [source,shell] .... # chmod 555 /usr/local/libexec/lf2crlf .... Modifique o [.filename]#/etc/printcap# para usar o novo filtro: [.programlisting] .... :if=/usr/local/libexec/lf2crlf:\ .... Teste o filtro imprimindo o mesmo arquivo de texto simples. O procedimento fará com que cada linha comece no lado esquerdo da página. [[printing-lpd-filters-enscript]] ==== Texto simples chique em impressoras PostScript(TM) com package:print/enscript[] O GNUEnscript converte arquivos de texto simples em arquivos formatados como PostScript(TM) para impressão em impressoras PostScript(TM). Ele adiciona números de página, quebra as linhas longas e fornece vários outros recursos para facilitar a leitura dos arquivos de texto impressos. Dependendo do tamanho do papel local, instale o package:print/enscript-letter[] ou o package:print/enscript-a4[] da coleção Ports. Crie o [.filename]#/usr/local/libexec/enscript# com este conteúdo: [.programlisting] .... #!/bin/sh /usr/local/bin/enscript -o - .... Defina as permissões e torne-o executável: [source,shell] .... # chmod 555 /usr/local/libexec/enscript .... Modifique o [.filename]#/etc/printcap# para usar o novo filtro: [.programlisting] .... :if=/usr/local/libexec/enscript:\ .... Teste o filtro imprimindo um arquivo de texto simples. [[printing-lpd-filters-ps2pcl]] ==== Imprimindo PostScript(TM) em impressoras PCL Muitos programas produzem documentos PostScript(TM). No entanto, impressoras baratas geralmente só entendem texto simples ou PCL. Este filtro converte os arquivos PostScript(TM) para o formato PCL antes de enviá-los para a impressora. Instale o interpretador de PostScript(TM) Ghostscript, package:print/ghostscript9[], através da Coleção de Ports. Crie o [.filename]#/usr/local/libexec/ps2pcl# com este conteúdo: [.programlisting] .... #!/bin/sh /usr/local/bin/gs -dSAFER -dNOPAUSE -dBATCH -q -sDEVICE=ljet4 -sOutputFile=- - .... Defina as permissões e torne-o executável: [source,shell] .... # chmod 555 /usr/local/libexec/ps2pcl .... A entrada PostScript(TM) enviada para este script será processada e convertida em PCL antes de ser enviada para a impressora. Modifique o [.filename]#/etc/printcap# para usar este novo filtro de entrada: [.programlisting] .... :if=/usr/local/libexec/ps2pcl:\ .... Teste o filtro enviando um pequeno programa PostScript(TM) para ele: [source,shell] .... % printf "%%\!PS \n /Helvetica findfont 18 scalefont setfont \ 72 432 moveto (PostScript printing successful.) show showpage \004" | lpr .... [[printing-lpd-filters-smart]] ==== Filtros Inteligentes Um filtro que detecta o tipo de entrada e converte automaticamente para o formato correto da impressora pode ser muito conveniente. Os dois primeiros caracteres de um arquivo PostScript(TM) são geralmente `%!`. Um filtro pode detectar esses dois caracteres. Os arquivos PostScript(TM) podem ser enviados de forma inalterada para uma impressora PostScript(TM). Arquivos de texto podem ser convertidos para PostScript(TM) com o Enscript como mostrado anteriormente. Crie o [.filename]#/usr/local/libexec/psif# com este conteúdo: [.programlisting] .... #!/bin/sh # # psif - Print PostScript or plain text on a PostScript printer # IFS="" read -r first_line first_two_chars=`expr "$first_line" : '\(..\)'` case "$first_two_chars" in %!) # %! : PostScript job, print it. echo "$first_line" && cat && exit 0 exit 2 ;; *) # otherwise, format with enscript ( echo "$first_line"; cat ) | /usr/local/bin/enscript -o - && exit 0 exit 2 ;; esac .... Defina as permissões e torne-o executável: [source,shell] .... # chmod 555 /usr/local/libexec/psif .... Modifique o [.filename]#/etc/printcap# para usar este novo filtro de entrada: [.programlisting] .... :if=/usr/local/libexec/psif:\ .... Teste o filtro imprimindo PostScript(TM) e arquivos de texto simples. -[[printing-lpd-filters-othersmart]] -==== Outros Filtros Inteligentes - -Escrever um filtro que detecte muitos tipos diferentes de entrada e os formate corretamente é um desafio. O package:print/apsfilter[] da Coleção de Ports é um filtro "magico" inteligente que detecta dezenas de tipos de arquivos e os converte automaticamente para o PDL entendido pela impressora. Veja http://www.apsfilter.org[] para mais detalhes. - [[printing-lpd-queues]] === Múltiplas filas As entradas no [.filename]#/etc/printcap# são na verdade definições de _filas_. Pode haver mais de uma fila para uma única impressora. Quando combinadas com filtros, múltiplas filas fornecem aos usuários um maior controle sobre como seus trabalhos são impressos. Por exemplo, considere uma impressora laser PostScript(TM) em rede num escritório. A maioria dos usuários deseja imprimir texto simples, mas alguns usuários avançados querem poder imprimir diretamente os arquivos PostScript(TM). Duas entradas podem ser criadas para a mesma impressora no [.filename]#/etc/printcap#: [.programlisting] .... textprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/textprinter:\ :if=/usr/local/libexec/enscript:\ :lf=/var/log/lpd-errs: psprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/psprinter:\ :lf=/var/log/lpd-errs: .... Os documentos enviados para a fila `textprinter` serão formatados pelo filtro [.filename]#/usr/local/libexec/enscript# mostrado em um exemplo anterior. Usuários avançados podem imprimir arquivos PostScript(TM) em `psprinter`, onde nenhuma filtragem é feita. Esta técnica de múltiplas filas pode ser usada para fornecer acesso direto a todos os tipos de recursos da impressora. Uma impressora com um duplexador pode usar duas filas, uma para impressões em apenas um lado da folha e outra com um filtro que envia a seqüência de comandos para habilitar a impressão frente e verso e, em seguida, envia o arquivo recebido. [[printing-lpd-monitor]] === Monitoramento e controle de impressão Vários utilitários estão disponíveis para monitorar trabalhos de impressão e verificar e controlar a operação da impressora. [[printing-lpd-monitor-lpq]] ==== man:lpq[1] O man:lpq[1] mostra o status das tarefas de impressão de um usuário. Trabalhos de impressão de outros usuários não são mostrados. Mostra os trabalhos pendentes do usuário atual em uma única impressora: [source,shell] .... % lpq -Plp Rank Owner Job Files Total Size 1st jsmith 0 (standard input) 12792 bytes .... Mostra os trabalhos pendentes do usuário atual em todas as impressoras: [source,shell] .... % lpq -a lp: Rank Owner Job Files Total Size 1st jsmith 1 (standard input) 27320 bytes laser: Rank Owner Job Files Total Size 1st jsmith 287 (standard input) 22443 bytes .... [[printing-lpd-monitor-lprm]] ==== man:lprm[1] O man:lprm[1] é usado para remover trabalhos de impressão. Usuários normais só podem remover seus próprios trabalhos. O `root` pode remover qualquer um ou todos os trabalhos. Remova todos os trabalhos pendentes de uma impressora: [source,shell] .... # lprm -Plp - dfA002smithy dequeued cfA002smithy dequeued dfA003smithy dequeued cfA003smithy dequeued dfA004smithy dequeued cfA004smithy dequeued .... Remova um único trabalho de uma impressora. O man:lpq[1] é usado para encontrar o número do trabalho. [source,shell] .... % lpq Rank Owner Job Files Total Size 1st jsmith 5 (standard input) 12188 bytes % lprm -Plp 5 dfA005smithy dequeued cfA005smithy dequeued .... [[printing-lpd-monitor-lpc]] ==== man:lpc[8] O man:lpc[8] é usado para verificar e modificar o status da impressora. O `lpc` é seguido por um comando e um nome de impressora opcional. O parâmetro `all` pode ser usado em vez de um nome de impressora específico, e o comando será aplicado a todas as impressoras. Usuários normais podem visualizar o status com man:lpc[8]. Somente o `class="username">root` pode usar comandos que modificam o status da impressora. Mostrar o status de todas as impressoras: [source,shell] .... % lpc status all lp: queuing is enabled printing is enabled 1 entry in spool area printer idle laser: queuing is enabled printing is enabled 1 entry in spool area waiting for laser to come up .... Impedindo que uma impressora aceite novos trabalhos e fazendo com que ela comece a aceitar novos trabalhos novamente: [source,shell] .... # lpc disable lp lp: queuing disabled # lpc enable lp lp: queuing enabled .... Pare de imprimir, mas continue aceitando novos trabalhos. Em seguida, comece a imprimir novamente: [source,shell] .... # lpc stop lp lp: printing disabled # lpc start lp lp: printing enabled daemon started .... Reinicie uma impressora após alguma condição de erro: [source,shell] .... # lpc restart lp lp: no daemon to abort printing enabled daemon restarted .... Desative a fila de impressão e desative a impressão, com uma mensagem para explicar o problema aos usuários: [source,shell] .... # lpc down lp Repair parts will arrive on Monday lp: printer and queuing disabled status message is now: Repair parts will arrive on Monday .... Reative uma impressora que esteja inativa: [source,shell] .... # lpc up lp lp: printing enabled daemon started .... Veja man:lpc[8] para mais comandos e opções. [[printing-lpd-shared]] === Impressoras Compartilhadas As impressoras costumam ser compartilhadas por vários usuários em empresas e escolas. Recursos adicionais são fornecidos para tornar as impressoras compartilhadas mais convenientes. [[printing-shared-aliases]] ==== Aliases O nome da impressora é definido na primeira linha da entrada em [.filename]#/etc/printcap#. Nomes adicionais, ou _aliases_, podem ser adicionados após esse nome. Os aliases são separados do nome e um do outro por barras verticais: [.programlisting] .... lp|repairsprinter|salesprinter:\ .... Os aliases podem ser usados no lugar do nome da impressora. Por exemplo, os usuários do departamento de vendas imprimem em sua impressora com [source,shell] .... % lpr -Psalesprinter sales-report.txt .... Usuários do departamento de Reparos podem imprimir na _sua_ impressora com [source,shell] .... % lpr -Prepairsprinter repairs-report.txt .... Todos os documentos são impressos nessa única impressora. Quando o departamento de vendas cresce o suficiente para precisar de sua própria impressora, o alias pode ser removido da entrada da impressora compartilhada e usado como o nome de uma nova impressora. Os usuários nos dois departamentos continuam usando os mesmos comandos, mas os documentos de vendas são enviados para a nova impressora. [[printing-shared-headers]] ==== Páginas de cabeçalho Pode ser difícil para os usuários localizarem seus documentos na pilha de páginas produzidas por uma impressora compartilhada ocupada. _Páginas de cabeçalho_ foram criadas para resolver este problema. Uma página de cabeçalho com o nome de usuário e o nome do documento é impressa antes de cada trabalho de impressão. Estas páginas são por vezes chamadas de páginas _banner_ ou _separadoras_. A ativação das páginas de cabeçalho é diferente, dependendo se a impressora está conectada diretamente ao computador com um cabo USB, paralelo ou serial, ou se está conectada remotamente por uma rede. As páginas de cabeçalho em impressoras conectadas diretamente são ativadas removendo-se a linha `:sh:\` (Suprimir Cabeçalho) da entrada no [.filename]#/etc/printcap#. Essas páginas de cabeçalho usam apenas caracteres de feed de linha para novas linhas. Algumas impressoras precisarão do filtro [.filename]#/usr/shared/examples/printing/hpif# para evitar imprimir o texto em escada. O filtro configura impressoras PCL para imprimir retornos de carro e alimentações de linha quando um feed de linha é recebido. As páginas de cabeçalho das impressoras de rede devem ser configuradas na própria impressora. Entradas de página de cabeçalho no [.filename]#/etc/printcap# são ignoradas. As configurações geralmente estão disponíveis no painel frontal da impressora ou em uma página da web de configuração acessível com um navegador da web. [[printing-lpd-references]] === Referências Arquivos de exemplo: [.filename]#/usr/shared/examples/printing/#. O _Manual do Spooler de Impressora de Linha do 4.3BSD_, [.filename]#/usr/shared/doc/smm/07.lpd/paper.ascii.gz#. Páginas de manual: man:printcap[5], man:lpd[8], man:lpr[1], man:lpc[8], man:lprm[1], man:lpq[1]. [[printing-other]] == Outros sistemas de impressão Vários outros sistemas de impressão estão disponíveis, além do man:lpd[8]. Esses sistemas oferecem suporte para outros protocolos ou recursos adicionais. [[printing-other-cups]] === CUPS (Sistema de impressão comum UNIX(TM)) O CUPS é um sistema de impressão popular disponível em muitos sistemas operacionais. Usar o CUPS no FreeBSD está documentado em um artigo separado: extref:{cups}[CUPS] [[printing-other-hplip]] === HPLIP A Hewlett Packard fornece um sistema de impressão que suporta muitas de suas impressoras a jato de tinta e laser. O port é o package:print/hplip[]. A página principal da web está em http://hplipopensource.com/hplip-web/index.html[]. O port lida com todos os detalhes de instalação no FreeBSD. As informações de configuração são mostradas em http://hplipopensource.com/hplip-web/install/manual/hp_setup.html[]. [[printing-other-lprng]] === LPRng O LPRng foi desenvolvido como uma alternativa aprimorada para o man:lpd[8]. O port é package:sysutils/LPRng[]. Para detalhes e documentação, veja http://www.lprng.com/[]. diff --git a/documentation/content/zh-tw/books/handbook/printing/_index.adoc b/documentation/content/zh-tw/books/handbook/printing/_index.adoc index 5b03556b21..2b5d278b27 100644 --- a/documentation/content/zh-tw/books/handbook/printing/_index.adoc +++ b/documentation/content/zh-tw/books/handbook/printing/_index.adoc @@ -1,756 +1,751 @@ --- title: 章 9. 列印 part: 部 II. 一般作業 prev: books/handbook/kernelconfig next: books/handbook/linuxemu showBookMenu: true weight: 12 path: "/books/handbook/printing/" --- [[printing]] = 列印 :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 9 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/printing/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] 儘管很多人試圖淘汰列印功能,但列印資訊到紙上仍是一個重要的功能。列印由兩個基本元件組成,包含了資料傳送到印表機的方式以及印表機可以理解的資料形式。 [[printing-quick-start]] == 快速開始 基本的列印功能可以快速設定完成,列印機必須能夠列印純 ASCII 文字。若要列印其他類型的檔案,請參考 <>。 [.procedure] ==== . 建立一個目錄來儲存要被列印的檔案: + [source,shell] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... + . 以 `root` 建立 [.filename]#/etc/printcap# 內容如下: + [.programlisting] .... lp:\ :lp=/dev/unlpt0:\ <.> :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :lf=/var/log/lpd-errs: .... + <.> 此行是針對連接到 USB 埠的印表機。連接到並列或 "印表器 (Printer)" 埠的印表機要使用:直接連接到網路的印表機要使用:替換 _network-printer-name_ 為網路印表機的 DNS 主機名稱。 . 編輯 [.filename]#/etc/rc.conf# 加入下行來開啟 `lpd`: + [.programlisting] .... lpd_enable="YES" .... + 啟動服務: + [source,shell] .... # service lpd start Starting lpd. .... + . 測試列印: + [source,shell] .... # printf "1. This printer can print.\n2. This is the second line.\n" | lpr .... + [TIP] ====== 若列印的兩行未從左邊界開始,而是呈現 "階梯狀 (Stairstep)",請參考 <>。 ====== + 現在可以使用 `lpr` 來列印文字檔,只要在指令列給序檔案名稱,或者將輸出使用管線符號 (Pipe) 傳送給 `lpr`。 + [source,shell] .... % lpr textfile.txt % ls -lh | lpr .... ==== [[printing-connections]] == 印表機連線 印表機有許多方式可以連接到電腦,小型的桌面印表機會直接連接到電腦的 USB 埠,舊式的印表機會連接到並列 (Parallel) 或 "印表機 (Printer)" 埠,而有一部份印表機則是直接連接網路,讓印表機能夠給多台電腦共享使用,還有少部分印表機則是連接到較罕見的序列 (Serial) 埠。 FreeBSD 可以與這些類型的印表機溝通。 [[printing-connections-usb]] USB:: USB 印表機可以連接到電腦上任何可用的 USB 埠。 + 當 FreeBSD 偵測到 USB 印表機,會建立兩個裝置項目:[.filename]#/dev/ulpt0# 以及 [.filename]#/dev/unlpt0#,傳送到兩者任一裝置的資料都會被轉發到印表機。在每個列印工作完成後 [.filename]#ulpt0# 便會重設 USB 埠,重設 USB 埠可能會在部份印表機造成問題,因此通常可以改使用 [.filename]#unlpt0# 裝置。[.filename]#unlpt0# 不會重設 USB 埠。 [[printing-connections-parallel]] 並列 (IEEE-1284):: 並列埠裝置使用 [.filename]#/dev/lpt0#,此裝置不論印表機是否連接上都會存在,它並不會自動偵測。 + 供應商已不再採用這種 "舊式" 連接埠,且有許多電腦甚至已沒有這種連接埠。可以用轉接器來連接並列印表機到 USB 埠,有了轉接器,並列印表機可以被當作 USB 印表機使用。有另一種稱作 _列印伺服器 (Print server)_ 的裝置也可用來連接並列印表機到網路。 [[printing-connections-serial]] 序列 (RS-232):: 序列埠也是另一種舊式連接埠,已很少用在印表機上,除了某些特殊的應用外,纜線、接頭與需要的佈線方式依需求變化性很大。 + 內建在主機板的序列埠的序列裝置名稱為 [.filename]#/dev/cuau0# 或 [.filename]#/dev/cuau1#。也有序列 USB 轉接器可使用,而裝置的的名稱則會是 [.filename]#/dev/cuaU0#。 + 要與序列印表機通訊必須知道數個通訊參數,其中最重要的是 _傳輸速率 (Baud rate)_ 或 BPS (Bits Per Second) 以及 _同位檢查 (Parity)_。數值有數種,但一般序列印表機會使用 的傳輸速率是 9600 且無同位檢查。 [[printing-connections-network]] 網路:: 網路印表機可直接連接到區域網路。 + 若印表機透過 DHCP 分配動態位址,則必須要知道 DNS 主機名稱,DNS 應動態更新來讓主機名稱能夠對應到正確的 IP 位址。指定網路印表機一個靜態的 IP 位址可避免這個問題。 + 大多數網路印表機可以認得使用 LPD 通訊協定所送出的列印工作,列印佇列 (Print queue) 的名稱也會在這時指定。部份印表機會依據使用的佇列來決定處理資料的方式,例如 `raw` 佇列會列印原始資料,而 `text` 佇列則會在純文字上增加換行符號 (Carriage return)。 + 大部份網路印表機也可列印直接傳送到埠號 9100 的資料。 [[printing-connections-summary]] === 摘要 有線網路連線通常是安裝最簡單的方式,且可以提供快速的列印。若要直接連接到電腦,較建議使用 USB,由於較快速、簡單。並列連線仍然可以使用,但有纜線長度與速度上的限制。而序列連線則比較難設定,不同型號的纜線佈線方式不同,且通訊參數如傳輸速率及同位檢查增加了複雜性,所幸序列印表機並不多。 [[printing-pdls]] == 常見的頁面描述語言 傳送給印表機的資料必須使用印表機能夠理解的語言,這些語言稱為頁面描述語言 (Page Description Languages) 或 PDL。 [[print-pdls-ascii]] ASCII:: 純 ASCII 文字是傳送資料到印表機最簡單的方式,一個字元對應一個要列印的文字:資料中的 `A` 會列印一個 `A` 在頁面。可以使用的格式非常少,沒有辦法選擇字型或者比例間距。強迫使用簡單的純 ASCII 為的是讓文字可以直接從電腦列印只需一點或甚至不需要編碼或轉譯,列印的結果可直接對應傳送的內容。 + 部份便宜印表機無法列印純 ASCII 文字,這讓這些印表機較難設定。 [[print-pdls-postscript]] PostScript(TM):: PostScript(TM) 與 ASCII 幾乎相反,與簡單的文字不同,PostScript(TM) 程式語言有一套指令可以繪出最終所要的文件,可以使用不同的字型與圖形,但是,這樣強大的功能是有代價的,繪製頁面需要搛寫程式語言,通常這個程式語言會由應用程式產生,所以使用者是看不到的。 + 便宜的印表機有時會移除 PostScript(TM) 的相容性來節省成本。 [[print-pdls-pcl]] PCL (Printer Command Language):: PCL 由 ASCII 延伸而來,加入了跳脫序列 (Escape sequence) 來標示格式、選擇字型以及列印圖型。大部份印表機都支援 PCL5,少數支援較新的 PCL6 或 PCLXL,這些後來的版本是 PCL5 的超集合 (Superset),並可以提供更快的列印速度。 [[print-pdls-host-based]] 以主機為基礎 (Host-Based):: 製造商可能會使用簡單的處理器和較小的記憶體來降低印表機的成本,這些印表機無法列印純文字,相反的,文字與圖形會先在機器上的驅動程式畫完後傳送到印表機。這些稱為__以主機為基礎 (Host-based)__ 的印表機。 + 驅動程式與以主機為基礎的印表機通訊通常會透過專用或無文件的通訊協定,這讓這些印表機只能在最常用的作業系統上運作。 [[print-pdls-table]] === 轉換 PostScript(TM) 至其他 PDL Port 套件集與 FreeBSD 工具集有許多可以處理 PostScript(TM) 輸出的應用程式,此表整理出了可轉換 PostScript(TM) 成其他常用 PDL 的工具: [[print-pdls-ps-to-other-tbl]] .輸出 PDL 格式 [cols="1,1,1", frame="none", options="header"] |=== <| 輸出 PDL <| 產生由 <| 說明 |PCL 或 PCL5 |package:print/ghostscript9-base[] |單色使用 `-sDEVICE=ljet4`、彩色使用 `-sDEVICE=cljet5` |PCLXL 或 PCL6 |package:print/ghostscript9-base[] |單色使用 `-sDEVICE=pxlmono`、彩色使用 `-sDEVICE=pxlcolor` |ESC/P2 |package:print/ghostscript9-base[] |`-sDEVICE=uniprint` |XQX |package:print/foo2zjs[] | |=== [[print-pdls-summary]] === 摘要 要可以列印最簡單的方式就是選擇支援 PostScript(TM) 的印表機,再來是支援 PCL 的印表機,有了 package:print/ghostscript9-base[] 這些印表機也可像原生支援 PostScript(TM) 的印表機一般使用。有直接支援 PostScript(TM) 或 PCL 的印表機通常也會直接支援純 ASCII 文字檔案。 行列式印表機如同典型的噴墨式印表機通常不支援 PostScript(TM) 或 PCL,這種印表機通常可以列印純 ASCII 文字檔案。package:print/ghostscript9-base[] 支援部份這種印表機使用的 PDL,不過要在這種印表機上列印完全以圖型為基礎的頁面通常會非常緩慢,由於需要傳送大量的資料並列印。 以主機為基礎的印表機通常較難設定,有些會因為用了專用的 PDL 而無法使用,盡可能避免使用這類的印表機。 有關各種 PDL 的介紹可至 http://www.undocprint.org/formats/page_description_languages[]。各種型號印表機所使用的特定 PDL 可至 http://www.openprinting.org/printers[] 查詢。 [[printing-direct]] == 直接列印 對於偶爾列印,檔案可以直接傳送到印表機裝置,無需做任何設定。例如,要傳送一個名稱為 [.filename]#sample.txt# 的檔案到 USB 印表機: [source,shell] .... # cp sample.txt /dev/unlpt0 .... 要直接使用網路印表機列印需看該印表機支援的功能,但大多數會接受埠號 9100 的列印作業,可使用 man:nc[1] 來完成。要使用 DNS 主機名稱為 _netlaser_ 的印表機列印與上述相同的檔案可: [source,shell] .... # nc netlaser 9100 < sample.txt .... [[printing-lpd]] == LPD (行列式印表機 Daemon) 在背景列印一個檔案稱作 _Spooling_,緩衝程式 (Spooler) 讓使用者能夠繼續執行電腦的其他程式而不需要等候印表機緩慢的完成列印工作。 FreeBSD 內含的緩衝程式 (Spooler) 稱作 man:lpd[8],而列印工作會使用 man:lpr[1] 來提交。 [[printing-lpd-setup]] === 初始設定 建立要用來儲存列印工作的目錄、設定擁有關係以及權限來避免其他使用者可以檢視這些檔案的內容: [source,shell] .... # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp .... 印表機會定義在 [.filename]#/etc/printcap#,每台印表機項目所包含的詳細資料有名稱、連接的接頭以及各種其他設定。建立 [.filename]#/etc/printcap# 使用以下內容: [.programlisting] .... lp:\ <.> :lp=/dev/unlpt0:\ <.> :sh:\ <.> :mx#0:\ <.> :sd=/var/spool/lpd/lp:\ <.> :lf=/var/log/lpd-errs: <.> .... <.> 印表機的名稱。 man:lpr[1] 會傳送列印工作到 `lp` 印表機,除非有使用 `-P` 來指定其他印表機,所以預的印表機名稱應使用 `lp`。 <.> 印表機所連接到裝置。替換此行為正確的連線類型,如此處所示。 <.> 在列印工作開始時不列印首頁。 <.> 不限制列印工作的最大尺寸。 <.> 此印表機的緩衝 (Spooling) 目錄路徑,每台印表機會自己使用一個獨立的緩衝 (Spooling) 目錄。 <.> 回報此印表機的錯誤的日誌檔。 在建立 [.filename]#/etc/printcap# 之後,使用 man:chkprintcap[8] 測試印表機是否有錯誤: [source,shell] .... # chkprintcap .... 在繼續之前修正任何回報的問題。 開啟 [.filename]#/etc/rc.conf# 中的 man:lpd[8]: [.programlisting] .... lpd_enable="YES" .... 啟動服務: [source,shell] .... # service lpd start .... [[printing-lpd-lpr]] === 使用 man:lpr[1] 列印 Documents are sent to the printer with `lpr`. A file to be printed can be named on the command line or piped into `lpr`. These two commands are equivalent, sending the contents of [.filename]#doc.txt# to the default printer: [source,shell] .... % lpr doc.txt % cat doc.txt | lpr .... Printers can be selected with `-P`. To print to a printer called _laser_: [source,shell] .... % lpr -Plaser doc.txt .... [[printing-lpd-filters]] === 過濾器 The examples shown so far have sent the contents of a text file directly to the printer. As long as the printer understands the content of those files, output will be printed correctly. Some printers are not capable of printing plain text, and the input file might not even be plain text. _Filters_ allow files to be translated or processed. The typical use is to translate one type of input, like plain text, into a form that the printer can understand, like PostScript(TM) or PCL. Filters can also be used to provide additional features, like adding page numbers or highlighting source code to make it easier to read. The filters discussed here are _input filters_ or _text filters_. These filters convert the incoming file into different forms. Use man:su[1] to become `root` before creating the files. Filters are specified in [.filename]#/etc/printcap# with the `if=` identifier. To use [.filename]#/usr/local/libexec/lf2crlf# as a filter, modify [.filename]#/etc/printcap# like this: [.programlisting] .... lp:\ :lp=/dev/unlpt0:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :if=/usr/local/libexec/lf2crlf:\ <.> :lf=/var/log/lpd-errs: .... <.> `if=` identifies the _input filter_ that will be used on incoming text. [TIP] ==== The backslash _line continuation_ characters at the end of the lines in [.filename]#printcap# entries reveal that an entry for a printer is really just one long line with entries delimited by colon characters. An earlier example can be rewritten as a single less-readable line: [.programlisting] .... lp:lp=/dev/unlpt0:sh:mx#0:sd=/var/spool/lpd/lp:if=/usr/local/libexec/lf2crlf:lf=/var/log/lpd-errs: .... ==== [[printing-lpd-filters-stairstep]] ==== 避免在純文字印表機階梯狀列印 Typical FreeBSD text files contain only a single line feed character at the end of each line. These lines will "stairstep" on a standard printer: [.programlisting] .... A printed file looks like the steps of a staircase scattered by the wind .... A filter can convert the newline characters into carriage returns and newlines. The carriage returns make the printer return to the left after each line. Create [.filename]#/usr/local/libexec/lf2crlf# with these contents: [.programlisting] .... #!/bin/sh CR=$'\r' /usr/bin/sed -e "s/$/${CR}/g" .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/lf2crlf .... Modify [.filename]#/etc/printcap# to use the new filter: [.programlisting] .... :if=/usr/local/libexec/lf2crlf:\ .... Test the filter by printing the same plain text file. The carriage returns will cause each line to start at the left side of the page. [[printing-lpd-filters-enscript]] ==== 使用 package:print/enscript[] 在 PostScript(TM) 印表機美化純文字內容 GNUEnscript converts plain text files into nicely-formatted PostScript(TM) for printing on PostScript(TM) printers. It adds page numbers, wraps long lines, and provides numerous other features to make printed text files easier to read. Depending on the local paper size, install either package:print/enscript-letter[] or package:print/enscript-a4[] from the Ports Collection. Create [.filename]#/usr/local/libexec/enscript# with these contents: [.programlisting] .... #!/bin/sh /usr/local/bin/enscript -o - .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/enscript .... Modify [.filename]#/etc/printcap# to use the new filter: [.programlisting] .... :if=/usr/local/libexec/enscript:\ .... Test the filter by printing a plain text file. [[printing-lpd-filters-ps2pcl]] ==== 列印 PostScript(TM) 到 PCL 印表機 Many programs produce PostScript(TM) documents. However, inexpensive printers often only understand plain text or PCL. This filter converts PostScript(TM) files to PCL before sending them to the printer. 由 Port 套件集安裝 Ghostscript PostScript(TM) 直譯器,package:print/ghostscript9-base[]。 Create [.filename]#/usr/local/libexec/ps2pcl# with these contents: [.programlisting] .... #!/bin/sh /usr/local/bin/gs -dSAFER -dNOPAUSE -dBATCH -q -sDEVICE=ljet4 -sOutputFile=- - .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/ps2pcl .... PostScript(TM) input sent to this script will be rendered and converted to PCL before being sent on to the printer. Modify [.filename]#/etc/printcap# to use this new input filter: [.programlisting] .... :if=/usr/local/libexec/ps2pcl:\ .... Test the filter by sending a small PostScript(TM) program to it: [source,shell] .... % printf "%%\!PS \n /Helvetica findfont 18 scalefont setfont \ 72 432 moveto (PostScript printing successful.) show showpage \004" | lpr .... [[printing-lpd-filters-smart]] ==== 智慧過濾器 A filter that detects the type of input and automatically converts it to the correct format for the printer can be very convenient. The first two characters of a PostScript(TM) file are usually `%!`. A filter can detect those two characters. PostScript(TM) files can be sent on to a PostScript(TM) printer unchanged. Text files can be converted to PostScript(TM) with Enscript as shown earlier. Create [.filename]#/usr/local/libexec/psif# with these contents: [.programlisting] .... #!/bin/sh # # psif - Print PostScript or plain text on a PostScript printer # IFS="" read -r first_line first_two_chars=`expr "$first_line" : '\(..\)'` case "$first_two_chars" in %!) # %! : PostScript job, print it. echo "$first_line" && cat && exit 0 exit 2 ;; *) # otherwise, format with enscript ( echo "$first_line"; cat ) | /usr/local/bin/enscript -o - && exit 0 exit 2 ;; esac .... Set the permissions and make it executable: [source,shell] .... # chmod 555 /usr/local/libexec/psif .... Modify [.filename]#/etc/printcap# to use this new input filter: [.programlisting] .... :if=/usr/local/libexec/psif:\ .... Test the filter by printing PostScript(TM) and plain text files. -[[printing-lpd-filters-othersmart]] -==== 其他智慧過濾器 - -Writing a filter that detects many different types of input and formats them correctly is challenging. package:print/apsfilter[] from the Ports Collection is a smart "magic" filter that detects dozens of file types and automatically converts them to the PDL understood by the printer. See http://www.apsfilter.org[] for more details. - [[printing-lpd-queues]] === 多序列 The entries in [.filename]#/etc/printcap# are really definitions of _queues_. There can be more than one queue for a single printer. When combined with filters, multiple queues provide users more control over how their jobs are printed. As an example, consider a networked PostScript(TM) laser printer in an office. Most users want to print plain text, but a few advanced users want to be able to print PostScript(TM) files directly. Two entries can be created for the same printer in [.filename]#/etc/printcap#: [.programlisting] .... textprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/textprinter:\ :if=/usr/local/libexec/enscript:\ :lf=/var/log/lpd-errs: psprinter:\ :lp=9100@officelaser:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/psprinter:\ :lf=/var/log/lpd-errs: .... Documents sent to `textprinter` will be formatted by the [.filename]#/usr/local/libexec/enscript# filter shown in an earlier example. Advanced users can print PostScript(TM) files on `psprinter`, where no filtering is done. This multiple queue technique can be used to provide direct access to all kinds of printer features. A printer with a duplexer could use two queues, one for ordinary single-sided printing, and one with a filter that sends the command sequence to enable double-sided printing and then sends the incoming file. [[printing-lpd-monitor]] === 監視與控制列印 Several utilities are available to monitor print jobs and check and control printer operation. [[printing-lpd-monitor-lpq]] ==== man:lpq[1] man:lpq[1] shows the status of a user's print jobs. Print jobs from other users are not shown. Show the current user's pending jobs on a single printer: [source,shell] .... % lpq -Plp Rank Owner Job Files Total Size 1st jsmith 0 (standard input) 12792 bytes .... Show the current user's pending jobs on all printers: [source,shell] .... % lpq -a lp: Rank Owner Job Files Total Size 1st jsmith 1 (standard input) 27320 bytes laser: Rank Owner Job Files Total Size 1st jsmith 287 (standard input) 22443 bytes .... [[printing-lpd-monitor-lprm]] ==== man:lprm[1] man:lprm[1] is used to remove print jobs. Normal users are only allowed to remove their own jobs. `root` can remove any or all jobs. Remove all pending jobs from a printer: [source,shell] .... # lprm -Plp - dfA002smithy dequeued cfA002smithy dequeued dfA003smithy dequeued cfA003smithy dequeued dfA004smithy dequeued cfA004smithy dequeued .... Remove a single job from a printer. man:lpq[1] is used to find the job number. [source,shell] .... % lpq Rank Owner Job Files Total Size 1st jsmith 5 (standard input) 12188 bytes % lprm -Plp 5 dfA005smithy dequeued cfA005smithy dequeued .... [[printing-lpd-monitor-lpc]] ==== man:lpc[8] man:lpc[8] is used to check and modify printer status. `lpc` is followed by a command and an optional printer name. `all` can be used instead of a specific printer name, and the command will be applied to all printers. Normal users can view status with man:lpc[8]. Only `root` can use commands which modify printer status. Show the status of all printers: [source,shell] .... % lpc status all lp: queuing is enabled printing is enabled 1 entry in spool area printer idle laser: queuing is enabled printing is enabled 1 entry in spool area waiting for laser to come up .... Prevent a printer from accepting new jobs, then begin accepting new jobs again: [source,shell] .... # lpc disable lp lp: queuing disabled # lpc enable lp lp: queuing enabled .... Stop printing, but continue to accept new jobs. Then begin printing again: [source,shell] .... # lpc stop lp lp: printing disabled # lpc start lp lp: printing enabled daemon started .... Restart a printer after some error condition: [source,shell] .... # lpc restart lp lp: no daemon to abort printing enabled daemon restarted .... Turn the print queue off and disable printing, with a message to explain the problem to users: [source,shell] .... # lpc down lp Repair parts will arrive on Monday lp: printer and queuing disabled status message is now: Repair parts will arrive on Monday .... Re-enable a printer that is down: [source,shell] .... # lpc up lp lp: printing enabled daemon started .... See man:lpc[8] for more commands and options. [[printing-lpd-shared]] === 分享印表機 Printers are often shared by multiple users in businesses and schools. Additional features are provided to make sharing printers more convenient. [[printing-shared-aliases]] ==== 別名 The printer name is set in the first line of the entry in [.filename]#/etc/printcap#. Additional names, or _aliases_, can be added after that name. Aliases are separated from the name and each other by vertical bars: [.programlisting] .... lp|repairsprinter|salesprinter:\ .... Aliases can be used in place of the printer name. For example, users in the Sales department print to their printer with [source,shell] .... % lpr -Psalesprinter sales-report.txt .... Users in the Repairs department print to _their_ printer with [source,shell] .... % lpr -Prepairsprinter repairs-report.txt .... All of the documents print on that single printer. When the Sales department grows enough to need their own printer, the alias can be removed from the shared printer entry and used as the name of a new printer. Users in both departments continue to use the same commands, but the Sales documents are sent to the new printer. [[printing-shared-headers]] ==== 頁首 It can be difficult for users to locate their documents in the stack of pages produced by a busy shared printer. _Header pages_ were created to solve this problem. A header page with the user name and document name is printed before each print job. These pages are also sometimes called _banner_ or _separator_ pages. Enabling header pages differs depending on whether the printer is connected directly to the computer with a USB, parallel, or serial cable, or is connected remotely over a network. Header pages on directly-connected printers are enabled by removing the `:sh:\` (Suppress Header) line from the entry in [.filename]#/etc/printcap#. These header pages only use line feed characters for new lines. Some printers will need the [.filename]#/usr/shared/examples/printing/hpif# filter to prevent stairstepped text. The filter configures PCL printers to print both carriage returns and line feeds when a line feed is received. Header pages for network printers must be configured on the printer itself. Header page entries in [.filename]#/etc/printcap# are ignored. Settings are usually available from the printer front panel or a configuration web page accessible with a web browser. [[printing-lpd-references]] === 參考文獻 Example files: [.filename]#/usr/shared/examples/printing/#. The _4.3BSD Line Printer Spooler Manual_, [.filename]#/usr/shared/doc/smm/07.lpd/paper.ascii.gz#. Manual pages: man:printcap[5], man:lpd[8], man:lpr[1], man:lpc[8], man:lprm[1], man:lpq[1]. [[printing-other]] == 其他列印系統 Several other printing systems are available in addition to the built-in man:lpd[8]. These systems offer support for other protocols or additional features. [[printing-other-cups]] === CUPS (Common UNIX(TM) Printing System) CUPS is a popular printing system available on many operating systems. Using CUPS on FreeBSD is documented in a separate article: extref:{cups}[CUPS] [[printing-other-hplip]] === HPLIP Hewlett Packard provides a printing system that supports many of their inkjet and laser printers. The port is package:print/hplip[]. The main web page is at http://hplipopensource.com/hplip-web/index.html[]. The port handles all the installation details on FreeBSD. Configuration information is shown at http://hplipopensource.com/hplip-web/install/manual/hp_setup.html[]. [[printing-other-lprng]] === LPRng LPRng was developed as an enhanced alternative to man:lpd[8]. The port is package:sysutils/LPRng[]. For details and documentation, see http://www.lprng.com/[].