- How can I convert a series of images to a PDF from the command line on Linux? [closed]
- 2 Answers 2
- 4 способа конвертировать JPG в PDF в Linux
- В этой статье
- Способ 1. JPG в PDF в Linux с помощью ImageMagick
- Способ 2. JPG в PDF в Linux с помощью LibreOffice
- Способ 3. JPG в PDF в Linux с помощью Gscan2PDF
- Способ 4. JPG в PDF в Linux с помощью PDF2Go (OCR)
- How to Convert Multiple Images to PDF in Ubuntu Linux
- Method 1: Use LibreOffice to combine multiple images into PDF
- Method 2: Use gscan2pdf GUI tool to convert multiple images to PDF
- Method 3: Using command line to convert multiple images to PDF
- Did it work for you?
- Convert images to PDF on Linux
- ImageMagick
- LibreOffice
- Conclusion
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.
4 способа конвертировать JPG в PDF в Linux
Вот 4 эффективных способа конвертировать JPG в PDF в Linux: с помощью ImageMagick, LibreOffice, Gscan2PDF и PDF2Go.
Василий Лебедев
Существует 4 различных способа, которые можно использовать для преобразования файла JPG в файл PDF в Linux. Но не волнуйтесь, эта статья покажет вам, как максимально эффективно использовать каждый способ.
В этой статье
Способ 1. JPG в PDF в Linux с помощью ImageMagick
Вы должны будете выполнить следующие действия, если хотите преобразовать JPG в PDF с помощью ImageMagick (включая несколько JPG в PDF).
Шаг 1. Щелкните правой кнопкой мыши на рабочем столе и выберите параметр «Открыть терминал здесь».
Шаг 2. Чтобы конвертировать фотографии в PDF, просто используйте команду конвертировать:
$ 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
Шаг 3. Используйте команду mogrify с параметром -format для преобразования нескольких фотографий. Все файлы JPG в каталоге /home/ubuntu будут преобразованы в файлы PDF с помощью этой команды:
$ mogrify -format pdf /home/ubuntu/*.jpg
$ mogrify -format pdf -path /home/data /home/ubuntu/*.jpg
Шаг 4. Вы можете использовать вышеупомянутую команду в сценарии оболочки для автоматизации преобразования JPG в PDF, как показано ниже. Создайте новый сценарий оболочки:
$ sudo vi jpg_to_pdf.sh
#!/bin/sh
$ mogrify -format pdf /home/ubuntu/*.jpg
Шаг 5. Затем документ можно сохранить и закрыть. Чтобы разрешить доступ, используйте следующую формулу:
$ sudo chmod +x jpg_to_pdf.sh
$ ./jpg_to_pdf.sh
Шаг 6. Вы даже можете настроить cronjob для запуска вышеупомянутого скрипта в 10 утра каждый день. Чтобы войти в crontab, просто выполните следующую команду.
$ crontab –e
0 10 * * * sudo ./jpg_to_pdf >/dev/null 2>&1
Шаг 7. Сохраните и закройте файл.
Способ 2. JPG в PDF в Linux с помощью LibreOffice
Если вы хотите преобразовать JPG в PDF с помощью LibreOffice, вы должны сделать следующее:
Шаг 1. Перейдите в LibreOffice и выберите «LibreOffice Draw».
Шаг 2. Вставьте туда свое изображение.
Шаг 3. Нажмите на вкладку «Файл», затем выберите «Экспортировать как», а затем «Экспортировать как PDF».
Шаг 4. Нажмите значок «Экспорт».
Шаг 5. Нажмите кнопку «Сохранить».
Способ 3. JPG в PDF в Linux с помощью Gscan2PDF
Если вы хотите преобразовать JPG в PDF с помощью Gscan2PDF, вы должны сделать следующее:
Шаг 1. Откройте Gscan2PDF и нажмите на значок папки.
Шаг 2. Выберите, какие фотографии будут заменены.
Шаг 3. Выберите вариант «Сохранить» в меню «Файл».
Шаг 4. Выберите параметр «PDF», а затем нажмите кнопку «Сохранить», чтобы сохранить его в нужном месте.
Способ 4. JPG в PDF в Linux с помощью PDF2Go (OCR)
Вы должны будете выполнить следующие действия, если хотите преобразовать JPG в PDF с помощью PDF2Go.
Шаг 1. Скопируйте URL-адрес изображения, которое нужно преобразовать в PDF2Go. Вы также можете отправить свою фотографию с помощью селектора папок.
Шаг 2. Появится полоса загрузки. Когда вы закончите, ваш экран будет разделен. Вы всегда можете увидеть свое изображение в правой части страницы, а текст, который вы извлекли, — в правой.
Шаг 3. Чтобы настроить язык вашего проекта, нажмите кнопку рядом с символом папки.
How to Convert Multiple Images to PDF in Ubuntu Linux
You have several documents or images scanned individually and you need to save multiple images to one PDF file.
You may find several websites that allow you to do that. But they are either not free or they will put their watermark on the final PDF file. And in any case, I don’t want to upload my documents to some random web server.
I had this need when I had to apply for a job and they required me to upload a single PDF file consisting of several documents. My problem was that I had documents scanned individually but not in one file.
It’s just one of the examples where you may need to convert multiple image files in one PDF file.
In Linux, there are several ways you can combine multiple images into a single PDF file.
- LibreOffice Draw or even Writer can be used to combine multiple images into PDF
- gscan2pdf graphical tool can also be used combining multiple images (and single page PDFs) into a single PDF one.
- The versatile ImageMagic command line tool can be used for converting images into PDF.
I’ll show all the above three methods in this tutorial.
Method 1: Use LibreOffice to combine multiple images into PDF
Open the LibreOffice Draw tool. This is a very handy tool and you can even edit PDF files with it. It is already preinstalled in most distributions so I am not going to discuss the LibreOffice installation in Ubuntu.
The idea here is to add your images in the pages and when you have everything set as per your desire, export everything as PDF. Not only image files, you can also add single page PDF file and combine them together with images into a single PDF file.
You can add new pages, insert images or PDF files (also inserted with insert image option) in those pages and then hit the PDF on the top. You’ll have a single PDF file with multiple images with all the images in it.
That was simple. Want even simpler? Use gscan2pdf which is explained in the next section.
Method 2: Use gscan2pdf GUI tool to convert multiple images to PDF
gscan2pdf is a utility that was created for scanning documents, quickly edit them and saving them in PDF. You don’t need a scanner to use it. Simply open it and add images to it.
gscan2pdf is a popular tool and it should be available in the repository of most Linux distributions. You can use your distribution’s package manager or software center to install it.
In Ubuntu, you can find it in the Software Center or use the apt command to install it.
Open a terminal using Ctrl+Alt+T shortcut and use the following command to install gscan2pdf:
sudo apt install gscan2pdf
Once installed, open gscan2pdf by searching for it in the menu
Once gscan2pdf is opened, you can select all the required files in it by clicking on the Open Files.
By default, it is arranged in alphabetical order but you can drag and drop to reorder the images as per your choice.
Once done, you can click on the Save icon to save the files to PDF.
When you hit the save button, the next screen might look confusing. Actually it provides you option of putting metadata in the document such as author, date etc similar to a word document.
If you just want a PDF file, hit the save button. Since the default output file is PDF, you don’t need to bother a lot here. Just choose where to save the converted file.
Since it is Linux, there is always a way to do the same thing in the terminal. Let me show the command line way of converting images into PDF in the next section.
Method 3: Using command line to convert multiple images to PDF
If you want to go the command line way, you can use ImageMagick. It’s very easy to convert several images into one PDF file this way as well.
Open a terminal and install ImageMagick using the command below:
sudo apt-get install imagemagick
Once you have it installed, use the ‘convert’ command line tool of ImageMagick. Just provide the paths to individual images and at the end of the command, name the output file. For example, something like this:
convert image1.jpg image2.png image3.bmp output.pdf
That’s it. Nothing more to be done. Cool isn’t it? 🙂
Did it work for you?
I hope this article helped you to merge multiple images into one PDF in Ubuntu Linux. If you are further interested, check this article to know how to edit PDF files in Ubuntu Linux.
Questions, suggestions, a word of thanks is always encouraged.
Convert images to PDF on Linux
The first option on our list is to use gscan2pdf app. Gscan2pdf is an open-source app available on all Linux distros and makes converting images to PDF a breeze. We can install it by going to the software centre and searching for gscan2pdf .
After opening the app, click on a folder icon to load images. An error pop-up might show up informing you that you don’t have scanning devices. That’s not a problem, just close it.
Having loaded images, you can customize them if you would like to do so.
The top toolbar includes editing options like:
Once we are done with editing, we can convert images into a single PDF:
File → Save → Select Document type to PDF → Save.
ImageMagick
ImageMagick is a CLI tool which allows you to convert images to PDF. As a CLI tool, it’s much faster than Gscan2pdf. On top of that, we can automate the whole process!
We can install it with the following command:
sudo apt install imagemagick
After installing it, convert your images to PDF with the following command:
convert \*.jpg my_pdf.pdf # All JPG files include in my_pdf.pdf file
The command above might yield an “operation not allowed” error. Fortunately, we can easily fix it by executing:
sudo sed -i 's/^.*policy.*coder.*none.*PDF.\*//' /etc/ImageMagick-6/policy.xml
After applying the fix, re-run the conversion command!
LibreOffice
The last option on our list is LibreOffice. LibreOffice Draw provides us with a bit cumbersome, but still possible way to convert images to PDF.
The biggest advantage of this approach is also its biggest disadvantage — the ability to arrange images on a page manually. If you just want to have each image on its page without much tweaking, then you should not use LibreOffice Draw for this.
You can import images in LibreOffice Draw by dragging and dropping them from your file manager and customize them as you wish.
Once we’ve finished with editing, we can export our work as PDF:
File → Export as → Export as PDF → Export
Conclusion
In this post, we’ve explored three different ways to convert images to PDF and discussed the pros and cons of each. What is your approach? Share your thoughts with us in the comments section below. 👇