- How can I convert a series of images to a PDF from the command line on Linux? [closed]
- 2 Answers 2
- How to Convert Image to PDF on Linux Command Line
- 1. ImageMagick
- 2. Img2PDF
- Conclusion
- About the author
- Denis Kariuki
- Как конвертировать документы в формат PDF в командной строке Ubuntu
- Почему именно командная строка?
- Использование LibreOffice CLI ‘Lowriter’ для преобразования pdf-файлов
- Преобразование одного файла в формат PDF
- Пакетное преобразование файлов в pdf
- Похожие записи:
- Four Ways to Convert JPG to PDF On Linux
- In this article
- Method 1. JPG to PDF in Linux with PDFelement
- Method 1. JPG to PDF in Linux with ImageMagick
- Method 2. JPG to PDF in Linux with LibreOffice
- Method 3. JPG to PDF in Linux with Gscan2PDF
- Method 4. JPG to PDF in Linux with PDF2Go (OCR)
How can I convert a series of images to a PDF from the command line on Linux? [closed]
I have a scanning server I wrote in CGI and Bash. I want to be able to convert a bunch of images (all in one folder) to a PDF from the command line. How can that be done?
Use img2pdf, not ImageMagick. ImageMagick decodes the JPEG, resulting in generation loss and is 10–100 times slower than img2pdf.
img2pdf $(find . -iname ‘*.jpg’ | sort -V) -o ./document.pdf will give you document.pdf containing all images with jpg or JPG extension in the current dir — one image per page. document.pdf will have all images ordered as pages naturally ( -V option for sort ) so there is no need to add any leading zeros when numbering image files.
2 Answers 2
what if page*.png does not sort the images in the way you want ? e.g. page_1.png, page_2.png . page_10.png -> page_10 will appear before page_1
To sort the files, you can use: ls page*.png | sort -n | tr ‘\n’ ‘ ‘ | sed ‘s/$/\ mydoc.pdf/’ | xargs convert
FYI you almost never need to use ls for anything apart from displaying files. i.e. do not parse it’s output. find is a much more suitable tool. Here is an example convert $(find -maxdepth 1 -type f -name ‘page*.png’ | sort -n | paste -sd\ ) output.pdf . Keep in mind that the aforementioned command will not work if your pathnames contain spaces. The addition of characters that need to be escaped makes things a little more complicated.
This is simple and works very well, thank you! To avoid generating huge PDF files, use something like convert -compress jpeg -quality 85 *.png out.pdf
ImageMagick decodes the JPEG, resulting in generation loss. Use img2pdf instead; it’s also 10–100 times faster.
How to Convert Image to PDF on Linux Command Line
Often, you may need to convert or add the images to the PDF files, especially if you have an application and you want the users to download the images as PDF files.
There are different online tools that convert the images to PDF. But security is always a concern, and you can’t trust these online sites with your data. The best method is to convert the images on your machine. Linux offers various command-line utilities to aid you with that. The two common tools are Img2PDF and ImageMagick.
1. ImageMagick
ImageMagick stands out for the image conversion to PDF for its fast speed. The open-source Linux tool utilizes the multiple CPU threads to keep the conversion process fast. Whether converting one image or multiple images, ImageMagick gets the job done.
Let’s first install ImageMagick using the following command:
$ sudo apt install -y imagemagick
For Fedora users, the command is as follows:
With the ImageMagick already installed, navigate to the directory containing your pictures. We have different images in our example. We will see how we can convert them one by one and how to convert them all at once.
The syntax for conversion is as following:
Note that we are using convert, a utility for ImageMagick. Let’s start by converting one image.
If you run the previous convert command, it should work fine. However, you may end up with an error message like the one reflected in the following image:
In that case, all you need is to edit the policy.xml file using an editor like nano.
Look for the line in the following example:
To fix the error, replace the rights from “none” to “read|write”
Save the file and rerun the command. You will now have a PDF file of the converted image.
To convert all the images in the current directory to PDF, you can add their names one by one or select the image format if they are the same. In our case, the image formats are in “.jpg”. In this case, our command is as follows:
That’s it! You now have all your images converted into one PDF.
ImageMagick is a great tool for converting the images to PDF on the command line. The only bad side of it is that the resolution for the images changes and the PDF file doesn’t have the full resolution, reducing the image quality.
2. Img2PDF
The ImageMagick converts the images to PDF, but the quality of the images reduces. The alternative is to use the Img2PDF to convert the same photos without losing the image quality. Besides, Img2PDF allows the specification of the image size when converting.
Start by installing Img2PDF using the following command:
You can verify the installation by checking the version.
Img2PDF can also be installed using pip in other distributions:
With the tool installed, let’s proceed to convert our images. We use the same pictures as we did with ImageMagick. First, navigate to the directory that contains your images. To convert a single file, use the following syntax:
We now have a PDF version of the image. If you want to convert multiple images, you can list them all. Or if they have the same format, use the * shorthand like in the following example:
To specify the page size or the image size for the output, use the –imgsize or –pagesize.
For instance, to specify the image size to 30cm by 45cm, the command is:
Conclusion
Converting the images of different formats to PDF shouldn’t trouble you when using Linux. There are command-line utilities at your disposal, and the syntax is easy. This guide has presented two utilities, Img2PDF and ImageMagick, that you can use to convert either one or multiple images to PDF.
About the author
Denis Kariuki
Denis is a Computer Scientist with a passion for Networking and Cyber Security. I love the terminal, and using Linux is a hobby. I am passionate about sharing tips and ideas about Linux and computing.
Как конвертировать документы в формат PDF в командной строке Ubuntu
PDF или Portable Document Format — это, в основном, первый выбор, когда речь идет о печати, совместном использовании и пересылке по электронной почте документов, особенно больших. Для Windows и macOS вы можете быть очень хорошо знакомы, а также зависимы от широко используемых продуктов Acrobat для создания, просмотра и редактирования PDF. К сожалению, в системах Linux нет стандартного специализированного pdf-создателя. Однако вы можете использовать продукты LibreOffice для создания PDF файлов в Ubuntu. В этой статье мы расскажем, как использовать командную строку Ubuntu, Терминал, для конвертирования и пакетного преобразования файлов .doc и .docx в их pdf-версии.
Почему именно командная строка?
Если вы пользуетесь Терминалом, то вам не захочется покидать уют командной строки и переходить в другое место для выполнения повседневных технических действий. Всегда есть способ сделать почти все наши вещи прямо в Терминале. Так почему же конвертация pdf должна быть иной! Использование Терминала делает некоторые задачи более эффективными и даже быстрыми. Инструменты командной строки не потребляют слишком много ресурсов и поэтому являются отличной альтернативой широко используемым графическим приложениям, особенно если у вас устаревшее оборудование.
Использование LibreOffice CLI ‘Lowriter’ для преобразования pdf-файлов
LibreOffice Write является частью пакета LibreOffice и в большинстве дистрибутивов Linux доступен по умолчанию. Если в вашей системе его нет, вы можете легко установить его из Ubuntu Software Manager:
Здесь мы будем использовать CLI для преобразования наших документов в pdf.
Вот как вы можете использовать Lowriter:
Откройте командную строку Ubuntu, Терминал, либо через поиск Ubuntu Application Launcher, либо с помощью сочетания клавиш Ctrl+Alt+T.
Убедитесь, что lowriter установлен в вашей системе, выполнив следующую команду:
Преобразование одного файла в формат PDF
Используйте следующий синтаксис команды для преобразования одного файла, расположенного в текущем каталоге:
lowriter --convert-to pdf filename.doc
lowriter --convert-to filename.docx
Вот как я преобразовал файл .docx в pdf, расположенный в папке Downloads.
Как вы можете видеть выше, когда я перечислил содержимое моей текущей папки с помощью команды ls, я увидел только что преобразованный файл pdf.
Пакетное преобразование файлов в pdf
Используйте следующий синтаксис команды для пакетного преобразования всех файлов .doc или .docx в pdf, расположенных в текущем каталоге:
lowriter --convert-to pdf *.doc
Для файлов .docx используйте:
lowriter --convert-to pdf *.docx
Вот как вы можете использовать CLI LibreOffice Writer для преобразования документов из .doc и .docx в pdf. Не требуется никаких дополнительных установок или длительных процедур, и вы получаете именно то, что вам нужно: преобразование .doc/.docx в pdf прямо через командную строку Ubuntu.
Похожие записи:
Four Ways to Convert JPG to PDF On Linux
There are five different methods that you can utilize in order to convert a JPG file into a PDF file on Linux. But do not worry, this article will show you the way to make the most of each method.
In this article
Method 1. JPG to PDF in Linux with PDFelement
Wondershare PDFelement is a PDF editor that works on Linux, Windows, macOS, iOS, and Android. This application provides an intuitive interface for you to convert JPG to PDF and edit PDF in a straightforward way. Here is how to convert JPG to PDF in Linux using PDFelement.
Step 1. Click the button below to download PDFelement.
Step 2. After installing PDFelement on your computer, run the application and click Create a PDF > from File and select the JPG that you want to convert PDF. Then the file will be turned into PDF. Save the PDF file.
You can convert JPG to PDF in batch with Batch Create in PDFelement. Just add as many JPG files as you need and convert them to PDF in one click.
Method 1. JPG to PDF in Linux with ImageMagick
You will have to follow these steps if you want to convert JPG to PDF with ImageMagick (including multiple JPG to PDF).
Step 1. Make a right-click on your desktop and then pick the ‘Open terminal here’ option.
Step 2. To convert photos to PDF, just use the convert command:
$ sudo convert /path/to/image /path/to/pdf
$ sudo convert /home/ubuntu/flower.jpg to /home/files/flowers.pdf
$ sudo vi /etc/ImageMagick-6/policy.xml
Step 3. Use the mogrify command with the -format option to convert multiple photos. All JPG files in the /home/ubuntu directory will be converted to PDF files with this command:
$ mogrify -format pdf /home/ubuntu/*.jpg
$ mogrify -format pdf -path /home/data /home/ubuntu/*.jpg
Step 4. You can use the aforementioned command in a shell script to automate JPG to PDF conversion, as demonstrated below. Make a new shell script:
$ sudo vi jpg_to_pdf.sh
#!/bin/sh
$ mogrify -format pdf /home/ubuntu/*.jpg
Step 5. The document may then be saved and closed. To enable access, use the following formula:
$ sudo chmod +x jpg_to_pdf.sh
$ ./jpg_to_pdf.sh
Step 6. You can even set up a cronjob to run the aforementioned script at 10 a.m. every day. To enter crontab, merely run the following command.
$ crontab –e
0 10 * * * sudo ./jpg_to_pdf >/dev/null 2>&1
Step 7. Save and close your file.
You can use the video given below to see how to convert JPG to PDF on Linux.
Method 2. JPG to PDF in Linux with LibreOffice
If you want to convert JPG to PDF with LibreOffice, you must do the following:
Step 1. Go to LibreOffice and select ‘LibreOffice Draw’.
Step 2. Paste your image there.
Step 3. Press on the ‘File’ tab, then select ‘Export as’ And then ‘Export as PDF’.
Step 4. Press on the ‘Export’ icon.
Step 5. Press on the ‘Save’ button.
Method 3. JPG to PDF in Linux with Gscan2PDF
If you wish to convert JPG to PDF with Gscan2PDF, you must do the following:
Step 1. Open Gscan2PDF and press on the folder icon.
Step 2. Choose which photographs will be replaced.
Step 3. Pick the ‘Save’ alternative from the ‘File’ menu.
Step 4. Choose the ‘PDF’ option and then hit the ‘Store’ button to save it to your preferred location.
Method 4. JPG to PDF in Linux with PDF2Go (OCR)
You will have to follow these steps if you want to convert JPG to PDF with PDF2Go.
Step 1. Copy the URL of the picture to be converted to PDF2Go. You may also submit your photograph using the folder selector.
Step 2. You will see that a loading bar appears. When you’re finished, your screen will be split. You can always see your picture on the hand side of the page, as well as the text you retrieved on the right.
Step 3. To adjust the language of your project, click on the button just beside the folder symbol.