Generate pdf with python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Simple PDF generation for Python

License

PyFPDF/fpdf2

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  Php sql odbc connection

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Co-authored-by: allcontributors[bot]

Git stats

Files

Failed to load latest commit information.

README.md

fpdf2 is a PDF creation library for Python:

from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font('helvetica', size=12) pdf.cell(txt="hello world") pdf.output("hello_world.pdf")

Go try it now online in a Jupyter notebook: or

Compared with other PDF libraries, fpdf2 is fast, versatile, easy to learn and to extend (example). It is also entirely written in Python and has very few dependencies: Pillow, defusedxml, & fontTools. It is a fork and the successor of PyFPDF (cf. history).

Development status: this project is mature and actively maintained.

We are looking for contributing developers: if you want to get involved but don’t know how, or would like to volunteer helping maintain this lib, open a discussion!

To get the latest, unreleased, development version straight from the development branch of this repository:

pip install git+https://github.com/PyFPDF/fpdf2.git@master
  • Python 3.7+ support
  • Unicode (UTF-8) TrueType font subset embedding
  • Internal / external links
  • Embedding images, including transparency and alpha channel
  • Arbitrary path drawing and basic SVG import
  • Embedding barcodes, charts & graphs, emojis, symbols & dingbats
  • Tables and also cell / multi-cell / plaintext writing, with automatic page breaks, line break and text justification
  • Choice of measurement unit, page format & margins. Optional page header and footer
  • Basic conversion from HTML to PDF
  • A templating system to render PDFs in batches
  • Images & links alternative descriptions, for accessibility
  • Table of contents & document outline
  • Document encryption & document signing
  • Annotations, including text highlights, and file attachments
  • Presentation mode with control over page display duration & transitions
  • Optional basic Markdown-like styling: **bold**, __italics__
  • Can render mathematical equations & charts
  • Usage examples with Django, Flask, FastAPI, streamlit, AWS lambdas. : Usage in web APIs
  • 1000+ unit tests running under Linux & Windows, with qpdf -based PDF diffing, timing & memory usage checks, and a high code coverage

Our 350+ reference PDF test files, generated by fpdf2 , are validated using 3 different checkers:

Choosing a project dependency can be difficult. We need to ensure stability and maintainability of our projects. Surveys show that GitHub stars count play an important factor when assessing library quality.

⭐ Please give this repository a star. It takes seconds and will help your fellow developers! ⭐

Please share with the community

This library relies on community interactions. Please consider sharing a post about fpdf2 and the value it provides 😊

  • Documentation Home
  • Tutorial in several languages: English — Deutsch — español — हिंदी — português — Русский — Italian — français — Ελληνικά — עברית — 简体中文 — বাংলা — ភាសខ្មែរ — 日本語
  • Release notes: CHANGELOG.md
  • A series of blog posts: fpdf2 tag @ ludochaordic

You can also have a look at the tests/ , they’re great usage examples!

This library could only exist thanks to the dedication of many volunteers around the world:

This project follows the all-contributors specification (emoji key). Contributions of any kind welcome!

Contributors map

(screenshot from January 2023, click on the map above to access an up-to-date online version)

Community, related tools, alternative libraries

Источник

Создание PDF при помощи PyFPDF и Python

ReportLab – это основной инструмент, который я использую для создания PDF с нуля. Однако, я заметил, что есть еще один — PyFPDF или FPDF для Python. Пакет PyFPDF – это порт «бесплатного» пакета PDF, который написан на PHP. Релиза этого проекта не было несколько лет, однако есть движения в его репозитории на Github, так что работа над проектом ведется. Пакет PyFPDF поддерживает Python 2.7 и Pyhton 3.4+.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

В данной статье не будет утомительных разборов пакета PyFPDF. Однако, мы раскроем более чем исчерпывающую информацию для эффективного использования. Обратите внимание на то, что существует небольшая книжечка «Python и PDF: pyFPDF» от Эдвуда Оказио на Leanpub, если вы захотите узнать больше о библиотеке, сверх той информации, которая указана в данной статье или документации пакета.

Установка

Установка PyFPDF – это просто, так как он подразумевает работу с pip. Установка проходит следующим образом:

На момент написания, эта команда устанавливала версию 1.7.2 на Python 3.6 без каких-либо проблем. Во время установки вы увидите, что этот пакет не имеет зависимостей, что приятно.

Базовое использование

Теперь, когда у вас есть установленный PyFPDF, попробуем использовать его для создания простого файла PDF. Откройте ваш редактор Python и создайте новый файл под названием **simple_demo.py**. После этого, введите следующий код:

Первый элемент, который нам нужно обсудить, это импорт. Здесь мы импортируем класс FPDF из пакета fpdf. Настройки по умолчанию этого класса создают PDF в режиме Portrait, используя миллиметры в качестве единицы измерения и размер страницы А4. Если вы хотите быть четче, вы можете вписать следующую строку установки:

Я не фанат использования буквы «P», чтобы указать классу, какая это ориентация. Вы можете использовать «L», если предпочитаете пейзаж вместо портрета.

Пакет PyFPDF поддерживает supports ‘pt’, ‘cm’ и ‘in’ в качестве альтернативных единиц измерения. Если обратиться к источнику, вы увидите, что пакет PyFPDF поддерживает только следующие размеры страниц:

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

В любом случае, следующий шаг – это создание страницы при помощи метода add_page. Далее, мы указываем шрифт при помощи метода set_font. Вы увидите, что мы передаем родительское наименование шрифта и размер, которые нам нужны. Вы также можете настроить стиль шрифта при помощи аргумента style. Если вы хотите сделать это, помните, что для этого нужна строка, такая как «В» для жирного шрифта, или «Bl» для полужирного.

Далее, мы создаем клетку, шириной 200 миллиметров и 10 миллиметров в высоту. Клетка, по большому счету, плавающая, и содержит текст, к ней можно подключить границы. Она разделяется автоматически, если включен автоматический разрыв страницы, так что клетка перейдет за границу страницы. Параметр txt – это текст, который вам нужно ввести в PDF. Параметр In указывает PyFPDF, что нужно добавить разрыв строки, если он указан как 1, что мы и делаем в нашей статье. Наконец, мы можем установить выравнивание текста по ширине (по умолчания), или по центру («С»). Здесь мы выбираем второй вариант.

Наконец, мы сохраняем документ на диск, вызывая метод output с путем к файлу, который мы хотим сохранить.
После запуска кода, мой PDF выглядит следующим образом:

Создание PDF при помощи PyFPDF и Python

Давайте попробуем узнать побольше о работе PyFPDF со шрифтами.

Работа со шрифтами

PyFPDF содержит набор базовых шрифтов, старательно прописанных в класс FPDF:

Источник

How to Create PDF in Python: A Comprehensive Guide

Create PDF using Python

Learn how to easily create a PDF in Python from scratch with this comprehensive guide. This tutorial provides you with the best but easiest solution for creating PDF files in a few simple steps. So get rid of writing complex code and explore how to generate PDF files with our powerful and high-speed PDF library for Python.

Let’s have a look at how to create a basic PDF and insert text into it programmatically. The following sections provide you with the steps and code samples of generating, opening, and saving PDF files in Python.

Python PDF Library#

To generate PDF files in Python, we will use Aspose.PDF for Python. It is an amazing PDF manipulation library that you can use to create, edit and process PDF files with ease. Use the following pip command to install the library from PyPI.

Once you have configured the library, you can proceed to create your first PDF file from scratch.

How to Create a PDF in Python#

The following are the steps to create a simple PDF file from scratch and insert a piece of text in it.

  • Create an instance of Document class.
  • Add a new page using Document.pages.add() method and get its reference in an object.
  • Create a new TextFragment object and set the text.
  • Add text to the page using Page.paragraphs.add(TextFragment) method.
  • Save the PDF file using Document.save(String) method.

The following code sample shows how to create a PDF file in Python.

Open a PDF in Python#

In certain cases, you have to process the existing PDF files. For such cases, Aspose.PDF lets you open a PDF file using the file’s path or stream object. Also, the library allows you to open an encrypted PDF file using its password.

The following sections demonstrate how to open a PDF file using Python in different ways.

Open a PDF File using Path#

The following Python code sample shows how to open a PDF using its path on disk.

Open a PDF using Stream#

You can also load and open a PDF using file stream in Python, as shown in the following code sample.

Open an Encrypted PDF#

Sometimes, you get the PDF file in encrypted form. To open an encrypted PDF, you need to provide the password. The following code sample shows how to open an encrypted PDF in Python.

Save PDF into PDF/A Format in Python#

PDF format supports various standards, e.g. PDF/A, and each of them provides as well as prohibits certain features. In case you want to save a PDF file in PDF/A standard, you can do it in a couple of steps. This is how you can save a PDF as PDF/A in Python.

  • Load the PDF file using Document class.
  • Use Document.convert() method to convert PDF to desired PDF/A format.
  • Save converted PDF using Document.save() method.

The following code sample shows how to save a PDF as PDF/A in Python.

Free Python PDF Generation Library#

You can get a free temporary license and generate PDF files from scratch without any limitations.

Python PDF Library — Read More#

You can explore more about the Python PDF library using documentation.

Conclusion#

In this article, you have learned how to create PDF files from scratch in Python. Furthermore, the Python code samples have demonstrated how to insert text in a PDF and open existing PDF files in different ways. Also, we have covered how to save a PDF file in PDF/A standard. You can easily install Aspose.PDF in your application and generate your desired PDF files.

See Also#

Источник

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