Linux file and print

How to Print files in Linux Using Command Line

Printing a file is one of the basic functionalities provide by the linux operating system, rather than just printing a file its provides us with a variety of options like to reformat it to adjust the margins, highlight some words, change text orientation and more. Undoubtedly we can print a file directly without passing any extra parameters but that would lead to a less appealing print, so here we see how to print a file and add optional parameters to make it look even better.

How to Print using pr command?

pr command is used as a basic command to print files, it has following syntax –

pr command does minor formatting to the input file you want to print by supplying options into the pr command, also pr command displays the file to user before printing it.

Here are the other options you can provide along with the pr command –

pr command options Usage
-k gives output in k columns
-t removes header and top/bottom margins from print
-d adds double spaces between the outputs
-h takes item to next header

Printing file where k=2, to print the output in 2 columns –

How to Print using lp/lpr command?

Unlike pr command, lp/lpr can be directly used to print out onto the printer without displaying the file on user’s terminal. Once you are ready with formatting using the pr command, you can use any of these commands to print your file on the printer connected to your computer.

To use lp command make sure you set the default printer, the lp command shows an ID that you can use to cancel the print job or check its status.

  • If you are using the lp command, you can use the -nNum option to print Num numberof copies. Along with the command lpr, you can use -Num for the same.
  • If there are multiple printers connected with the shared network, then you can choose a printer using -dprinter option along with lp command and for the same purpose you can use -Pprinter option along with lpr command. Here printer is the printer name.

Check and Abort file printing using lpstat and cancel command

lpstat command can be used to get a view of the printer’s queue, they may include – request IDs, owners, file sizes, when the jobs were sent for printing, and the status of the requests. We can use lpstat -o to see all output requests

The cancel command terminates a printing request from the lp command. The lprm command terminates all lpr requests. You can specify either the ID of the request (displayed by lp or lpq) or the name of the printer, to cancel whatever request is currently printing, regardless of its ID, simply enter cancel and the printer name –

Along with following commands there are even more commands like lpq (similar to lpstat) , lprm (command will cancel the active printing job if it belongs to you), etc.

Источник

Linux file and print

Printing from within an application is very easy, selecting the Print option from the menu.

From the command line, use the lp or lpr command.

These commands can read from a pipe, so you can print the output of commands using

There are many options available to tune the page layout, the number of copies, the printer that you want to print to if you have more than one available, paper size, one-side or double-sided printing if your printer supports this feature, margins and so on. Read the man pages for a complete overview.

Once the file is accepted in the print queue, an identification number for the print job is assigned:

> lp /etc/profile request id is blob-253 (1 file(s))

To view (query) the print queue, use the lpq or lpstat command. When entered without arguments, it displays the contents of the default print queue.

> lpq blob is ready and printing Rank Owner Job File(s) Total Size active davy 253 profile 1024 bytes davy:

> lpstat blob-253 davy 1024 Tue 25 Jul 2006 10:20_01 AM CEST

Which is the default printer on a system that has access to multiple printers?

> lpstat -d system default destination: blob

What is the status of my printer(s)?

> lpstat -p printer blob now printing blob-253. enabled since Jan 01 18:01

If you don’t like what you see from the status commands, use lprm or cancel to delete jobs.

In the graphical environment, you may see a popup window telling you that the job has been canceled.

In larger environments, lpc may be used to control multiple printers. See the Info or man pages on each command.

There are many GUI print tools used as a front-end to lp , and most graphical applications have a print function that uses lp . See the built-in Help functions and program specific documentation for more.

Printing on UNIX and alikes has a long history. There used to be two rather different approaches: the BSD-style printing and the SystemV-style printing. For compatibility, Linux with CUPS supports the commands from both styles. Also note that lp does not behave exactly like lpr , lpq has somewhat different options than lpstat and lprm is almost, but not quite, like cancel . Which one you use is not important, just pick the commands that you are comfortable with, or that you may know from previous experiences with UNIX-like systems.

If we want to get something sensible out of the printer, files should be formatted first. Apart from an abundance of formatting software, Linux comes with the basic UNIX formatting tools and languages.

Modern Linux systems support direct printing, without any formatting by the user, of a range of file types: text, PDF, PostScript and several image formats like PNG, JPEG, BMP and GIF.

For those file formats that do need formatting, Linux comes with a lot of formatting tools, such as the pdf2ps , fax2ps and a2ps commands, that convert other formats to PostScript. These commands can create files that can then be used on other systems that don’t have all the conversion tools installed.

Apart from these command line tools there are a lot of graphical word processing programs. Several complete office suites are available, many are free. These do the formatting automatically upon submission of a print job. Just to name a few: OpenOffice.org , KOffice , AbiWord , WordPerfect , etc.

The following are common languages in a printing context:

groff : GNU version of the UNIX roff command. It is a front-end to the groff document formatting system. Normally it runs the troff command and a post-processor appropriate for the selected device. It allows generation of PostScript files.

TeX and the macro package LaTeX : one of the most widely used markup languages on UNIX systems. Usually invoked as tex , it formats files and outputs a corresponding device-independent representation of the typeset document.

Technical works are still frequently written in LaTeX because of its support for mathematic formulas, although efforts are being made at W3C (the World Wide Web Consortium) to include this feature in other applications.

SGML and XML: Free parsers are available for UNIX and Linux. XML is the next generation SGML, it forms the basis for DocBook XML, a document system (this book is written in XML, for instance).

Why are there two commands for every task related to printing?

The man pages contain pre-formatted troff data which has to be formatted before it can roll out of your printer. Printing is done using the -t option to the man command:

man -t command > man-command.ps

Then print the PostScript file. If a default print destination is configured for your system/account, you can just issue the command man -t command to send the formatted page to the printer directly.

Anything that you can send to the printer can normally be sent to the screen as well. Depending on the file format, you can use one of these commands:

PostScript files: with the gv (GhostView) command.

TeX dvi files: with xdvi , or with KDE ‘s kdvi .

PDF files: xpdf , kpdf , gpdf or Adobe’s viewer, acroread , which is also available for free but is not free software. Adobe’s reader supports PDF 1.6, the others only support PDF versions up to 1.5. The version of a PDF file can be determined using the file command.

From within applications, such as Firefox or OpenOffice, you can usually select Print Preview from one of the menus.

Источник

Low Fat Linux

The lpr command makes a copy of your file and stuffs it in the system’s print queue (a process called spooling), so you can change or delete the original file without harming your printout.

The lpr command will accept two optional flags:

-r Delete the file after printing.

-s No spooling (don’t make a temporary copy for printing).

The -r flag tells the system to delete the file after printing, and -s tells the system to print directly from the original file instead of spooling to the print queue. Of course, if you specify the -s flag, you can’t modify or delete the original file while it’s printing, but this option can save a bit of time (since no copy is made) when the original file is big.

Here are some examples using the -r and -s flags:

lpr -r humongous Delete the file humongous after printing.

lpr -s humongous Print the file humongous without spooling.

lpr -r -s humongous Print the file humongous without spooling and t hen delete it.

Customizing Your Printouts

The lpr command is a no-frills way to print your files. It doesn’t do any fancy formatting; it just dumps your file on the printer. If you’d like to format your printout (paginate, add a title, set margins, or control the page length), you can use the pr command in conjunction with lpr. By default, pr will add page numbers and a title consisting of the file’s name and the date and time it was last modified. But you can do lots of other fancy formatting as well. Here are some of the options that pr supports:

-d Double-space the printout.

-h my title> Specify a title for the page header (the default is the file name).

-L n Set the page length to n lines (the default is 66).

-O n Set the margin to n characters (the default is 8).

-T Suppress the page header.

-2 | -3 | -4 Print output in two, three, or four columns (as in a newspaper).

Typically, the output from pr is sent only to your printer (by piping the output to lpr, as shown in the following examples), but if you leave off the lpr step, you’ll see the output on the screen instead. Here are some examples using the pr command to print a file named panda97.txt—for example, with no options specified, just adding page numbers and the default title (file name and date):

pr panda97.txt | lpr

Here we’ve specified a more meaningful title for the printout:

pr -h «Financial Report» panda97.dat | lpr

And now we’ve set the page length to 55 lines, set the margin to 5 spaces, and added double-spacing:

pr -h «Financial Report» -l55 -o5 -d panda97.dat | lpr

If you send a file to the printer by mistake, you might be able to snatch it from the print queue before it’s too late. First use lpq to find the job number:

lpq
Rank Owner Job Files Total Size
1st hermie 17 really-humongous 2317678 bytes

In the example shown here, the job number is 17. Once you know the job number, enlist the assistance of lprm to remove that file from the queue as follows (using job 17 as an example):

Источник

Печать из командной строки Linux

Оригинал: Printing from the Linux command line
Автор: Sandra Henry-Stocker
Дата публикации: 20 марта 2019 года
Перевод: А. Кривошей
Дата перевода: апрель 2016 г.

Печать из командной строки Linux очень проста. Вы используете команду lp, чтобы запросить печать, и lpq, чтобы увидеть, какие задания на печать находятся в очереди, но все становится немного сложнее, когда вы хотите печатать на двух сторонах листа или в портретном режиме. И есть много других вещей, которые вы можете захотеть сделать — например, распечатать несколько копий документа или отменить задание на печать. Давайте проверим некоторые опции, чтобы, когда вы печатаете из командной строки, ваши распечатки выглядели именно так, как вы хотите.

Вывод параметров принтера

Чтобы просмотреть настройки принтера из командной строки, используйте команду lpoptions. Вывод должен выглядеть примерно так:

Этот вывод, вероятно, будет немного более дружественным к человеку, если вы превратите его пробелы в возврат каретки. Обратите внимание, сколько настроек указано в списке.

ПРИМЕЧАНИЕ. В приведенном ниже выводе некоторые строки были повторно связаны, чтобы сделать этот вывод более читабельным.

С опцией -v команда lpinfo выведет список драйверов и связанной с ними информации.

Команда lpoptions покажет настройки вашего принтера по умолчанию. Используйте параметр -p, чтобы указать один из нескольких доступных принтеров.

Команда lpstat -p отображает состояние принтера, а команда lpstat -p -d также выводит список доступных принтеров.

Полезные команды

Чтобы распечатать документ на принтере по умолчанию, просто используйте команду lp, а затем имя файла, который вы хотите распечатать. Если имя файла содержит пробелы (что редко встречается в системах Linux), либо поместите имя в кавычки, либо начните вводить имя файла и нажмите клавишу табуляции, чтобы вызвать завершение файла (как показано во втором примере ниже).

Команда lpq отображает очередь печати.

Команда lp с опцией -n позволяет вам указать количество копий, которое вы хотите напечатать.

Чтобы отменить задание на печать, вы можете использовать команду cancel или lprm. Если вы не будете действовать быстро, то можете увидеть это:

Двусторонняя печать

Чтобы печатать в двухстороннем режиме, вы можете ввести команду lp с параметром sides, в котором указано, как печатать на обеих сторонах листа, и вид переплета (сбоку или сверху). Этот параметр представляет обычный способ, при которым вы получите двусторонний документ в портретном режиме.

Если вы хотите, чтобы все ваши документы печатались в двухстороннем режиме, вы можете изменить настройки lp для sides с помощью команды lpoptions.

Чтобы вернуться к односторонней печати, вы должны использовать такую команду:

Печать в ландшафтном режиме

Для печати в ландшафтном режиме вы должны использовать параметр landscape с командой lp.

Система печати, используемая в системах Linux, — это основанная на стандартах система печати с открытым исходным кодом, называемая CUPS, первоначально обозначавшая Common Unix Printing System. Она позволяет компьютеру выступать в качестве сервера печати.

Источник

Читайте также:  Долгая идентификация сети windows 10
Оцените статью
Printing documentation