Compress pdf file linux

Как уменьшить размер файла PDF в Linux

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

Утилиты для уменьшения размера файлов PDF в Linux

GhostScript

В Linux для сжатия PDF-файлов vj;yj использовать утилиту командной строки ghostscript.

Если команда недоступна на вашем компьютере, вы можете установить ее с помощью менеджера пакетов.

Например, в Ubuntu вы можете использовать apt:

sudo apt install ghostscript

Эта волшебная команда может сжимать PDF-файлы до читабельного качества:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dQUIET -dBATCH -sOutputFile=output.pdf input.pdf

Вместо output.pdf и input.pdf укажите имена соответствующих файлов.

В таблице ниже представлены различные флаги параметра -dPDFSETTINGS. Используйте их в соответствии с вашими потребностями.

Мы использовали приведенную выше команду для сжатия файла объемом 73 МБ до 14 МБ.

Утилита ps2pdf

Команда ps2pdf преобразует файл PDF в PS, а затем обратно, в результате эффективно сжимая его.

Это не всегда срабатывает, но иногда дает очень хорошие результаты.

ps2pdf input.pdf output.pdf

Чтобы получить наилучшую производительность, рекомендуем использовать параметр -dPDFSETTINGS=/ebooks, поскольку электронные книги имеют самый удобный для чтения размер, а также занимают достаточно мало места.

ps2pdf -dPDFSETTINGS=/ebook input.pdf output.pdf
Мы применили эту команду к PDF-файлу размером 73 МБ и получили те же результаты, что и с командой ghostscript: сжатый PDF-файл был размером всего 14 МБ!

Графические утилиты для уменьшения PDF-файлов в Linux

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

Densify

Densify — это графический интерфейс для ghostscript, который можно установить в любом дистрибутиве Linux, поскольку он использует Python3 и его модули GTK.

Мы создали простой bash-скрипт для выполнения всей необходимой работы. Запустите этот bash-скрипт от имени пользователя root, чтобы связать и загрузить необходимые файлы.

#!/bin/bash #- HELPER SCRIPT FOR DENSIFY #- original package https://github.com/hkdb/Densify #- script author Vijay Ramachandran #- site https://journaldev.com #- # Go to your home directory (preferred) cd $HOME # Download the package git clone https://github.com/hkdb/Densify cd Densify # Queue must be changed to queue in the file. # Will not work otherwise sed -i 's/Queue/queue/g' $PWD/densify # Create the symlink to /opt sudo ln -s $PWD /opt/Densify # Perform the install cd /opt/Densify sudo chmod 755 install.sh sudo ./install.sh # Export to PATH if [ $SHELL == "/bin/zsh" ]; then if test -f $HOME/.zshrc; then echo 'export PATH=/opt/Densify:$PATH' >> $HOME/.zshrc source $HOME/.zshrc else echo "No zshrc Found! Please create a zsh config file and try again" fi else if [ $SHELL == "/bin/bash" ]; then if test -f $HOME/.bashrc; then echo 'export PATH=/opt/Densify:$PATH' >> $HOME/.bashrc source $HOME/.bashrc else if test -f $HOME/.bash_profile; then echo 'export PATH=/opt/Densify:$PATH' >> $HOME/.bash_profile source $HOME/.bash_profile else echo "No bashrc Found! Please create a bash config file and try again" fi fi else echo "Default Shell is not zsh or bash. Please add /opt/Densify to your PATH" fi fi

Если при этом не возникает ошибок, просто введите приведенную ниже команду из opt/densify , чтобы запустить графический интерфейс, или откройте его через панель.

Читайте также:  Small damn linux iso

С помощью данного графического интерфейса вы можете сжимать любое необходимое вам количество PDF-файлов.

Дополнительную полезную информацию о сжатии вы найдете здесь .

Источник

How to Compress PDF in Linux [GUI & Terminal]

I was filling some application form and it asked to upload the necessary documents in PDF format. Not a big issue. I gathered all the scanned images and combined them in one PDF using gscan2pdf tool.

The problem came when I tried to upload this PDF file. The upload failed because it exceeded the maximum file size limit. This only meant that I needed to somehow reduce the size of the PDF file.

Now, you may use an online PDF compressing website but I don’t trust them. A file with important documents uploading to an unknown server is not a good idea. You could never be sure that they don’t keep a copy your uploaded PDF document.

This is the reason why I prefer compressing PDF files on my system rather than uploading it to some random server.

In this quick tutorial, I’ll show you how to reduce the size of PDF files in Linux. I’ll show both command line and GUI methods.

Method 1: Reduce PDF file size in Linux command line

Compress Pdf Linux

You can use Ghostscript command line tool for compressing a PDF file. Most Linux distributions include the open source version of Ghostscript already. However, you can still try to install it just to make sure.

On Debian/Ubuntu based distributions, use the following command to install Ghostscript:

sudo apt install ghostscript

Now that you have made sure that Ghostscript is installed, you can use the following command to reduce the size of your PDF file:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/prepress -dNOPAUSE -dQUIET -dBATCH -sOutputFile=compressed_PDF_file.pdf input_PDF_file.pdf

In the above command, you should add the correct path of the input and out PDF file.

The command looks scary and confusing. I advise copying and pasting most of it. What you need to know is the dPDFSETTINGS parameter. This is what determines the compression level and thus the quality of your compressed PDF file.

Читайте также:  Работа с командной строкой линукс
dPDFSETTINGS Description
/prepress (default) Higher quality output (300 dpi) but bigger size
/ebook Medium quality output (150 dpi) with moderate output file size
/screen Lower quality output (72 dpi) but smallest possible output file size

Do keep in mind that some PDF files may not be compressed a lot or at all. Applying compression on some PDF files may even produce a file bigger than the original. There is not much you can do in such cases.

Method 2: Compress PDF files in Linux using GUI tool

I understand that not everyone is comfortable with command line tool. The PDF editors in Linux doesn’t help much with compression. This is why we at It’s FOSS worked on creating a GUI version of the Ghostscript command that you saw above.

Panos from It’s FOSS team worked on creating a Python-Qt based GUI wrapper for the Ghostscript. The tool gives you a simple UI where you can select your input file, select a compression level and click on the compress button to compress the PDF file.

Compress Pdf

The compressed PDF file is saved in the same folder as the original PDF file. Your original PDF file remains untouched. The compressed file is renamed by appending -compressed to the original file name.

If you are not satisfied with the compression, you can choose another compression level and compress the file again.

You may find the source code of the PDF Compressor on our GitHub repository. To let you easily use the tool, we have packaged it in AppImage format. Please refer to this guide to know how to use AppImage.

Please keep in mind that the tool is in early stages of developments. You may experience some issues. If you do, please let us know in the comments or even better, file a bug here.

We’ll try to add more packages (Snap, Deb, PPAs etc) in the future releases. If you have experience with the development and packaging, please feel free to give us a hand.

Would you like It’s FOSS team to work on creating more such small desktop tools in future? Your feedback and suggestions are welcome.

Источник

How to Compress PDF File in Linux for Free

When you have a massive PDF file or a large number of PDF files to transfer, it is a better practice to compress PDF files. In Linux, there are various methods for compressing the PDF files like command-line tools and GUI tools for free.

This post will have a brief and step-by-step guide on how to compress a PDF file in Linux for free through the command line using GhostScript. GhostScript’s installation process and usage method are demonstrated on the Ubuntu 20.04 LTS system, and it can work on every other Debian-based operating system.

Читайте также:  Linux kernel module symbols

Compress PDF File in Linux Using GhostScript

Ghost Script is a command-line utility used for compressing the PDF files and for performing other PDF-related tasks.

Installation of GhostScript

To install GhostScript on Ubuntu or other Debian-based operating systems, it is a better practice to update and upgrade the system’s packages.

Execute the command provided below to begin the installation of GhostScript:

The GhostScript will be installed, and after the successful installation of Ghostscript, it’s time to understand the usage of GhostScript in Ubuntu.

Usage of Ghost Script Command

The syntax for compressing a PDF file using the GhostScript command is given below:

$ gs -sDEVICE =pdfwrite -dCompatibilityLevel = 1.4 -dPDFSETTINGS = / screen -dNOPAUSE -dQUIET -dBATCH -sOutputFile =output.pdf input.pdf

Most of the options need to stay as they are; our concern is with only two options:

-dPDFSETTINGS Option

For high-quality 300 DPI output, use /prepress setting.

For medium-quality output around 150 DPI, use /ebook setting.

For low-quality output around 72 DPI, use /screen setting.

-s OutputFile option

Provide the name of the output file that you want to give.

Lastly, at the end of the command, write down the PDF file you need to compress.

After executing the GhostScript command for compressing the PDF file, you will get the compressed PDF file within a few seconds based on the file size provided.

Example

Suppose we have a file.pdf in the downloads directory and we want to compress it, go to the specific directory where the file is placed.

Execute the GhostScript command provided below to compress the file.pdf:

$ gs -sDEVICE =pdfwrite -dCompatibilityLevel = 1.4 -dPDFSETTINGS = / screen -dNOPAUSE -dQUIET -dBATCH -sOutputFile =compressed.pdf file.pdf

Do not forget to change the PDF settings according to your choice. Input file name, and output file.

Once the file is compressed, execute the command given below to view the change in the size of the two files:

You can verify that the compressed file is smaller in size as compared to the original PDF file.

Conclusion

GhostScript is a command-line tool used for compressing PDF files in Linux. In this post, we have learned how to install the GhostScript on Ubuntu, how to compress a PDF file using the GhostScript, and how to use it and alter settings to extract the compressed PDF of our own choice.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.

Источник

Оцените статью
Adblock
detector