Linux print pdf file

Кунг-фу стиля Linux: PDF для пингвинов

Вначале PostScript представлял собой язык программирования для принтеров. И хотя PostScript-принтеры всё ещё не потеряли актуальности, существует и множество других форматов, в которых можно отправлять данные на печать. Но благодаря PostScript появился Portable Document Format — PDF, который стал невообразимо популярным. Пожалуй, не проходит и дня, чтобы каждый из нас не просмотрел бы какой-нибудь PDF-документ на своём компьютере. Конечно, есть и форматы, конкурирующие с PDF, но им, в сравнении с PDF, принадлежит лишь небольшая доля рынка. Просмотр PDF-файлов в Linux — это не проблема. А как насчёт их редактирования? Как оказалось, это тоже несложно, правда, только если знать о том, как именно это делается.

Графические инструменты

Существует множество инструментов для редактирования PDF-файлов в Linux. Главная проблема тут — качество получаемого результата. Для редактирования PDF-файлов можно воспользоваться, например, LibreOffice Draw, Inkscape или даже GIMP. Эти инструменты, как правило, отлично справляются с простыми задачами, например — когда нужно лишь убрать что-то из документа, перекрыв это белым прямоугольником, или когда надо сделать в документе какое-то примечание. А вот если речь идёт о более сложных изменениях, или о получении документов, элементы которых выверены до последнего пикселя, то эти инструменты для решения таких задач вполне могут и не подойти.

Редактирование PDF-документа в GIMP

Основная сложность тут в том, что большинство подобных инструментов работают с PDF-документами как с изображениями, или, как минимум, как с коллекциями объектов. Например, текстовые колонки, вероятно, будут преобразованы в наборы отдельных строк. Изменение чего-либо, что вызывает переход текста на новую строку, приведёт к необходимости ручного изменения других строк. А иногда то, что выглядит как текст, текстом, на самом деле, не является. Текст может быть представлен изображениями. Это сильно зависит в первую очередь от того, как именно был создан конкретный PDF-файл.

Если вы не против использования онлайн-инструментов, то вам, в деле работы с PDF, может пригодиться PDFEscape — бесплатный и весьма достойный редактор. Среди других вариантов можно отметить Scribus и Okular. Оба эти инструмента, на самом деле, не умеют редактировать файлы, но могут импортировать их в виде изображений, с которыми уже можно работать. Например, в Okular, в режиме предварительного просмотра документов, можно добавлять в документы аннотации, вроде тех, которыми отмечают самое интересное, и элементы, нарисованные от руки.

Неудивительно то, что emacs умеет выводить PDF-файлы при запуске под X. Можно использовать Control+C Control+C для переключения на просмотр текстового представления файла. В конце концов, большинство PDF-файлов представляют собой файлы, содержащие текст, а emacs поддерживает даже работу с бинарными файлами. Поэтому, если вы не против поработать с внутренним содержимым PDF-файлов, которое очень похоже на PostScript, вы можете редактировать PDF-файлы в emacs или в каком-нибудь другом текстовом редакторе.

Существует несколько специализированных платных PDF-редакторов и как минимум один опенсорсный редактор такого рода. Но, конечно, как и для решения большинства задач в Linux, для редактирования PDF-файлов можно пользоваться инструментами командной строки.

Маскировка текста

Проблема работы с PDF-файлами, представленными в виде обычного текста, заключается в том, что, даже при просмотре их emacs, текстовые данные в таких файлах часто сжаты и, в результате, нечитаемы. Например, буквы, из которых состоят слова, могут быть разделены кодом, форматирующим их, или другими данными. Поэтому поискать некий текст в подобных файлах, вполне возможно, не получится.

PDF-файлы можно конвертировать в формат, при использовании которого сжатие не слишком сильно портит текст, но это — тоже не панацея. Например, если открыть следующий фрагмент кода статьи про любительскую радиосвязь и задаться целью изменить слово «convention», то сложно будет понять даже то, где именно находится это слово. Но оно, тем не менее, где-то здесь:

3 0 obj > stream

Волшебство командной строки

Существует такой инструмент — qpdf , который умеет конвертировать PDF-файлы в другие PDF-файлы. Он может оптимизировать эти файлы в расчёте на их размещение в интернете или в расчёте на редактирование текста. Он умеет выполнять простые операции вроде удаления страниц или объединения фрагментов нескольких файлов. Вы можете взглянуть на документацию по нему. В вышеприведённом примере мы воспользовались режимом QDF для создания совершенно нормального PDF-файла, все объекты которого размещены в соответствии с их порядковыми номерами, в котором используется обычный для Unix способ завершения строк. Такие свойства выходных файлов упрощают их редактирование в обычных текстовых редакторах, но, как мы уже видели, это, всё равно, не такая уж и простая задача. Например, довольно-таки сложно удалить объект целиком, но если избавиться ото всех его упоминаний, то можно, воспользовавшись fix-qdf , воссоздать нормальный QDF-файл.

Читайте также:  Как взламывать с помощью linux

Ещё один способ выполнения простых правок PDF-документов предусматривает использование PDFtk Server (PDFtk, без «Server», это графический набор инструментов для Windows). С помощью PDFtk можно объединять или разделять документы, поворачивать страницы и решать много других распространённых задач. Например — вот как объединить все материалы двух файлов:

Можно сделать то же самое, но пропустив, скажем, страницу №9:

Ещё можно перемешивать страницы объединённых документов, располагая их в нужном порядке:

Путешествие из текста в PDF и обратно

Если нужно, пользуясь инструментами командной строки, преобразовать текст в PDF, решить эту задачу можно разными способами. Например, существует отличный инструмент Pandoc, который позволяет преобразовывать материалы, оформленные с помощью одних языков разметки, в материалы, оформленные с помощью других способов описания документов. В частности, речь идёт о возможности преобразования практически всего чего угодно в PDF.

Ещё можно использовать различные комбинации ps2pdf (вместе с инструментом для генерирования PostScript-данных), pdf2text (этот инструмент входит в состав пакета poppler-utils) или Ghostscript для создания PDF-файлов или для извлечения из них текстовых данных. Надо сказать, что Ghostscript — это весьма мощный инструмент, среди возможностей которого можно отметить преобразование PDF-файлов в различные графические форматы. Это может пригодиться, если нужно, например, выводить их на веб-страницах в виде изображений.

Инструменты для решения особых задач печати документов и другие инструменты

Иногда нужно модифицировать PDF-файл в расчёте на то, что он будет определённым образом выведен на печать. Мы уже говорили, например, о том, как совмещать нечётные и чётные страницы документов, но есть и другие способы подготовки документов к печати:

  • pdfxup — инструмент, задействующий возможности pdflatex и Ghostscript для размещения нескольких PDF-страниц (например — двух) на одной печатной странице.
  • pdfjam — использует LaTeX для размещения документов на страницах разных размеров или для вывода нескольких страниц документа на одной печатной странице.
  • pdfposter — умеет создавать печатные изображения огромных размеров на нескольких страницах, беря за основу одну страницу.

Если вы предпочитаете инструменты с графическим интерфейсом — можете взглянуть на PDFsam Basic. А если вас интересует ПО для работы с PDF, написанное на Java — обратите внимание на Multivalent.

Итоги

В Linux существует множество способов решения одних и тех же повседневных задач. Это справедливо и для задач, связанных с PDF-документами. Но иногда самое сложное заключается не в том, чтобы решить задачу, а в том, чтобы найти инструмент, который идеально подходит под требования и стиль работы пользователя.

Чем вы пользуетесь для редактирования PDF-файлов в Linux?

Источник

Linux print pdf file

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:

Читайте также:  Windows для флешки нетбук

> 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.

Источник

Going Linux

for computer users who just want to use Linux to get things done

Add a PDF Printer

Way back in Episode 2 of the podcast, we mentioned that, «Linux provides the ability to create (print) PDF files directly from almost any application, but not from within Firefox! Open the same web page in Konqueror, for example, and — no problem.» That was true in 2007 when we recorded that episode. In today’s Linux, you simply choose the «Print to File» option right there in the Print dialog box, and select the PDF option.

Printing from Modern Browsers

Most modern browsers use exactly the same print dialog box as any other application. A notable exception is the Chrome browser. It uses its own dialog box, and the selection Save as PDF is provided as an option.

Printing with Ancient Distributions or «Classic» Browsers

The advice in the remainder of this document still applies if you are using an older version of your Linux distribution, or if you have a browser that behaves the way Firefox did «in the old days» of Linux. With this kind of application (we’ll be nice and call them «classic» browsers) in order to be able to create PDF files from within any application that can print, there is an add-on package you will need to install. From within your package manager, search for and install the package «cups-pdf.»

In Episode 8 of the podcast, listener Mike P. described printing from an old version of Firefox in an old version of KDE with the cups-pdf package installed.

Here is Mike’s suggestion:

  1. When you have a page you want to print displayed in Firefox, select on File, Print. (or Ctrl+P)
  2. In the printer selection combo box, choose Postscript from the list of available or installed printers.
  3. Click the Properties button, then clear the command box and type in kprinter.
  4. Click on OK, then on Print and the print job will be passed on to the KDE printer where the option for PDF creation is there by default if you have cups-pdf installed.

Mike continues: From now on, whenever you choose Postscript from the Firefox printer dialogue, the kprinter option will be remembered. This will call up the kde printer dialogue and you can choose Print to PDF (file) or whatever else is available.

Add the CUPS-PDF virtual printer in KDE (These are some original instructions for Kubuntu 6.10)

As an alternative, you can create a virtual printer that allows you to «print» PDF files. Here is how to add the printer to KDE once cups-pdf is installed. In 2006, (Linux Neophyte wrote an excellent post on how to add cups-pdf under Gnome 2.)

  1. From the K-menu select System Settings.
  2. Choose Printers.
  3. Click on Add and choose Add Printer/Class.
  4. Click Next, select Other printer type and click Next.
  5. Choose Virtual Printer [PDF Printer] from the list and click Next.
  6. Select Generic as the Manufacturer.
  7. Select Postscript Printer as the Model and click Next.
  8. Continue to click Next until you are prompted to give the printer a name, and name whatever you would like. I named mine «CUPS-PDF.»
  9. Click Next then Finish and your new printer is ready for use.
  10. The PDF files you create with Ubuntu and Kubuntu will be located in the directory

/PDF. (That’s the PDF sub-directory in your home folder.)

Theme music for the Going Linux podcast is generously provided by Mark Blasco. https://www.podcastthemes.com
Going Linux Podcast by Larry Bushey is licensed under a Creative Commons Attribution 4.0 International License.

Источник

Читайте также:  Создать установочную флешку windows 10 через ультра исо
Оцените статью
Printing documentation