Przejdź do treści stopki
KORZYSTANIE Z IRONPDF FOR PYTHON

Jak tworzyć pliki PDF z tekstem i obrazami w języku Python

W dzisiejszej erze cyfrowej potrzeba generowania dokumentów PDF z dynamiczną treścią, w tym tekstem i obrazami, jest powszechnym wymogiem. Python to popularny język programowania, który ułatwia automatyzację rutynowych procesów, pozwalając zaoszczędzić czas i energię. Posiadanie wszechstronnej biblioteki do tworzenia plików PDF z tekstem i obrazami w języku Python może być bardzo przydatne do automatycznego generowania raportów, pokwitowań lub faktur. IronPDF, wszechstronna biblioteka języka Python, upraszcza proces tworzenia plików PDF o bogatej zawartości.

W tym artykule omówimy, jak używać IronPDF do generowania plików PDF zawierających zarówno tekst, jak i obrazy w projekcie w języku Python.

Jak tworzyć pliki PDF z tekstem i obrazami w języku Python

  1. Zainstaluj bibliotekę IronPDF for Python
  2. Utwórz instancję ChromePdfRenderer
  3. Dodaj treść tekstową
  4. Dodaj obraz jako dane binarne
  5. Utwórz ciąg HTML zawierający tekst i obrazy
  6. Renderowanie HTML do PDF za pomocą RenderHtmlAsPdf
  7. Zapisz plik PDF za pomocą metody SaveAs

Wprowadzenie do IronPDF

IronPDF to bogata w funkcje biblioteka języka Python, która zapewnia programistom potężne narzędzia do tworzenia, modyfikowania i przetwarzania dokumentów PDF. Dzięki IronPDF można z łatwością włączać tekst, obrazy, tabele i inne elementy do plików PDF, co czyni go cennym narzędziem do szerokiego zakresu zastosowań, od generowania raportów po tworzenie dokumentów.

How to Create PDF Files with Text and Images in Python: Figure 1 - IronPDF for Python: The Python PDF Library

Najważniejsze cechy IronPDF:

  • Łatwa integracja: IronPDF płynnie integruje się z popularnymi środowiskami programistycznymi Python, dzięki czemu jest dostępny dla programistów korzystających z narzędzi takich jak PyCharm.
  • Obsługa sformatowanego tekstu: Obsługuje formatowanie tekstu, umożliwiając programistom łatwe tworzenie atrakcyjnych wizualnie dokumentów PDF.
  • Obsługa obrazów: IronPDF umożliwia umieszczanie obrazów w plikach PDF, zapewniając elastyczność w projektowaniu i dostosowywaniu dokumentów.
  • Kompatybilność międzyplatformowa: IronPDF działa na różnych platformach, zapewniając spójne wyświetlanie i obsługę wygenerowanych plików PDF.

Wymagania wstępne

Zanim zaczniesz tworzyć dokumenty PDF za pomocą IronPDF, upewnij się, że spełniasz następujące wymagania wstępne:

  1. Zainstalowany Python: Python musi być zainstalowany na komputerze. Najnowszą wersję można pobrać i zainstalować z oficjalnej strony internetowej języka Python (https://www.python.org/).
  2. Środowisko IDE PyCharm: Użyj PyCharm lub dowolnego innego środowiska IDE dla języka Python. PyCharm to popularne zintegrowane środowisko programistyczne, które zapewnia wygodną przestrzeń roboczą do tworzenia oprogramowania w języku Python.
  3. IronPDF: biblioteka IronPDF pobrana stąd lub zainstalowana za pomocą PIP (Python Package Manager). Do prawidłowego korzystania z funkcji IronPDF wymagane jest również środowisko uruchomieniowe Microsoft .NET. Użytkownicy systemów Linux, Mac i Windows mogą pobrać wersję .NET 6.0, korzystając z tego linku do pobrania.

Utwórz projekt Python w PyCharm

Po spełnieniu wymagań wstępnych otwórz PyCharm i utwórz nowy projekt w języku Python. Skonfiguruj środowisko wirtualne dla swojego projektu, aby efektywnie zarządzać zależnościami.

  1. Kliknij Plik > Nowy projekt.
  2. W oknie "Nowy projekt":
    • Wpisz nazwę swojego projektu w polu "Lokalizacja".
    • Wybierz lokalizację, w której chcesz zapisać pliki projektu.
  3. W sekcji "Interpreter projektu" wybierz interpreter języka Python. Jeśli zainstalowałeś Pythona, program automatycznie wykryje interpreter Pythona.
  4. Wybierz typ projektu. W przypadku prostego projektu w języku Python można pozostać przy ustawieniach domyślnych.

    Jak tworzyć pliki PDF z tekstem i obrazami w języku Python: Rysunek 2 – Otwórz środowisko PyCharm IDE. Przejdź do menu Plik – kliknij opcję Nowy projekt. Enter the name and location for your Python project. Next, select the Python interpreter under Project Interpreter. Click on Create button to create the project. Once the Python project is created, open a new python file and use it to write code to generate PDF files using IronPDF.

  5. Click Create to create the project.
  6. Open a new python file and save it to write code to generate PDF files using Python library - IronPDF.

Install IronPDF for Python Using PIP

To install IronPDF, use the following PIP command in your project's terminal or command prompt:

pip install ironpdf

This command will automatically download and install the IronPDF library along with its dependencies.

How to Create PDF Files with Text and Images in Python: Figure 3 - To install IronPDF, use the following command in your project's terminal or command prompt: pip install ironpdf

Creating a Simple PDF with Text and Images

Let's walk through the steps to create a single PDF page document that includes both text and image using IronPDF:

Step 1: Import IronPDF

In this step, we import all the required modules from IronPDF. We import ChromePdfRenderer for rendering PDFs and base64 for encoding image data.

from ironpdf import ChromePdfRenderer
import base64
from ironpdf import ChromePdfRenderer
import base64
PYTHON

Step 2: Instantiate ChromePdfRenderer

Here, we will create an instance of the ChromePdfRenderer, which will be used to render the HTML content into a PDF.

# Instantiate Renderer
renderer = ChromePdfRenderer()
# Instantiate Renderer
renderer = ChromePdfRenderer()
PYTHON

Step 3: Add Text Content

In this step, we will define an HTML string (html_content) that includes the structure of the HTML document, including the header, body, and a section with text content that is later converted to a single PDF file. CSS styling is used to position the text and image.

# HTML String with Text 
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF Generation Example</title>
    <style>
        body {
            margin: 0; /* Remove default margin */
            padding: 20px; /* Add padding for better visibility */
            position: relative; /* Set the body as a relative position */
        }
        header {
            text-align: center;
        }
        section {
            margin-top: 20px; /* Add margin to separate sections */
        }
        img {
            position: absolute;
            top: 20px; /* Adjust the top position */
            right: 20px; /* Adjust the right position */
        }
    </style>
</head>
<body>
    <header>
        <h1>PDF Generation Example</h1>
    </header>
    <section id="contentSection">
        <h2>Text and Image in PDF</h2>
        <p>This PDF includes both text and an embedded image:</p>
        <p>IronPDF developed by Ironsoftware is a great PDF creating library for .NET, Python, JAVA, Node.JS.</p>
"""
# HTML String with Text 
html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF Generation Example</title>
    <style>
        body {
            margin: 0; /* Remove default margin */
            padding: 20px; /* Add padding for better visibility */
            position: relative; /* Set the body as a relative position */
        }
        header {
            text-align: center;
        }
        section {
            margin-top: 20px; /* Add margin to separate sections */
        }
        img {
            position: absolute;
            top: 20px; /* Adjust the top position */
            right: 20px; /* Adjust the right position */
        }
    </style>
</head>
<body>
    <header>
        <h1>PDF Generation Example</h1>
    </header>
    <section id="contentSection">
        <h2>Text and Image in PDF</h2>
        <p>This PDF includes both text and an embedded image:</p>
        <p>IronPDF developed by Ironsoftware is a great PDF creating library for .NET, Python, JAVA, Node.JS.</p>
"""
PYTHON

Step 4: Add Image

Here, we will open and read an image file (ironpdf-logo.png) in binary mode, convert it to a base64-encoded data URI, and embed it in the HTML string. The image is then positioned using CSS styles to appear in the top-right corner.

# Read image and convert to base64 string
with open("ironpdf-logo.png", "rb") as f:
    pngBinaryData = f.read()
    imgDataUri = "data:image/png;base64," + base64.b64encode(pngBinaryData).decode("utf-8")
    imgHtml = f"""
        <img src='{imgDataUri}' width=100px height=100px
            alt="IronPDF Logo">
    </section>
</body>
</html>
"""
# Read image and convert to base64 string
with open("ironpdf-logo.png", "rb") as f:
    pngBinaryData = f.read()
    imgDataUri = "data:image/png;base64," + base64.b64encode(pngBinaryData).decode("utf-8")
    imgHtml = f"""
        <img src='{imgDataUri}' width=100px height=100px
            alt="IronPDF Logo">
    </section>
</body>
</html>
"""
PYTHON

Step 5: Join Text and Image HTML String

This step concatenates the text and image HTML strings to create the complete HTML content (full_html_content) that will be rendered into a PDF output file.

full_html_content = html_content + imgHtml
full_html_content = html_content + imgHtml
PYTHON

Step 6: Render HTML Content as PDF File

Here, the RenderHtmlAsPdf method is used to convert the HTML to PDF using the ChromePdfRenderer.

# Create a PDF from the HTML string
pdf = renderer.RenderHtmlAsPdf(full_html_content)
# Create a PDF from the HTML string
pdf = renderer.RenderHtmlAsPdf(full_html_content)
PYTHON

Step 7: Save PDF File

Finally, the resulting PDF is saved as "output_with_text_and_image_top_right.pdf". This file will contain the formatted text and the embedded image positioned in the top-right corner.

# Save the PDF to a file
pdf.SaveAs("output_with_text_and_image_top_right.pdf")
# Save the PDF to a file
pdf.SaveAs("output_with_text_and_image_top_right.pdf")
PYTHON

Wynikowy dokument PDF

Now after executing the program, the output PDF file is as follows:

How to Create PDF Files with Text and Images in Python: Figure 4 - OUTPUT: output_with_text_and_image_top_right.pdf

Similarly, multiple PDF pages can be added to a PDF file with ease.

Advanced Usage: Customizing Text and Image Placement

IronPDF provides additional features for fine-tuning the placement and styling of text and images within the PDF using an external CSS/JavaScript file. The base path can be sent as an optional argument to the RenderHtmlAsPdf method as demonstrated in the following code:

# Advanced Example with HTML Assets
# Load external HTML assets: Images, CSS, and JavaScript.
# An optional BasePath 'C:\site\assets\' is set as the file location to load assets from.
myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", r"C:\site\assets")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
# Advanced Example with HTML Assets
# Load external HTML assets: Images, CSS, and JavaScript.
# An optional BasePath 'C:\site\assets\' is set as the file location to load assets from.
myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", r"C:\site\assets")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
PYTHON

In this advanced code example, we are taking the concept of embedding an image further through external sources. The HTML content within the RenderHtmlAsPdf method includes an  related to Advanced Usage: Customizing Text and Image Placementtag pointing to an image file (iron.png) located in the specified assets directory (C:\site\assets\). Additionally, this directory is set as the BasePath parameter.

In RenderHtmlAsPdf you can send a complete HTML web page as shown in the above steps. The CSS file can be referenced using the base path as the second optional parameter. For more detailed information on other ways of generating PDF format or modifying an existing PDF file, please visit the code examples and documentation page.

Wnioski

In this article, we explored how to use IronPDF to create PDF files with text and images in a Python project. With its intuitive API and powerful features, IronPDF empowers developers to generate dynamic and visually appealing PDF documents effortlessly. Whether you're creating reports, documentation, or any other type of content, IronPDF provides a reliable and flexible solution for PDF generation in Python. Experiment with the customization options to tailor your PDFs to specific design requirements, making IronPDF a valuable tool for your document generation needs.

IronPDF license or you can contact support for further queries.

How to Create PDF Files with Text and Images in Python: Figure 5 - IronPDF for Python License Information

You can download and install the library from IronPDF's website.

Często Zadawane Pytania

Jak mogę utworzyć plik PDF z tekstem i obrazami przy użyciu języka Python?

Możesz użyć biblioteki IronPDF ChromePdfRenderer do tworzenia plików PDF z tekstem i obrazami w języku Python. Najpierw zainstaluj bibliotekę IronPDF, a następnie utwórz ciąg HTML z żądaną treścią. Użyj metody RenderHtmlAsPdf, aby przekształcić HTML na PDF, a na koniec zapisz plik PDF za pomocą metody SaveAs.

Jakie kroki należy wykonać, aby zainstalować bibliotekę PDF do użytku w języku Python?

Aby zainstalować bibliotekę IronPDF for Python, można użyć menedżera pakietów PIP. Wystarczy uruchomić polecenie pip install ironpdf w wierszu poleceń lub terminalu, aby pobrać i zainstalować bibliotekę wraz z jej zależnościami.

Jakie warunki wstępne są wymagane do korzystania z biblioteki do tworzenia plików PDF w języku Python?

Na komputerze musi być zainstalowany Python, środowisko IDE, takie jak PyCharm do programowania, oraz biblioteka IronPDF. Dodatkowo, aby IronPDF działał, wymagane jest środowisko uruchomieniowe Microsoft .NET.

Czy możliwe jest dostosowywanie plików PDF przy użyciu zewnętrznych arkuszy CSS lub JavaScript z bibliotekami Python?

Tak, IronPDF umożliwia korzystanie z zewnętrznych plików CSS i JavaScript w celu dostosowania układu i wyglądu plików PDF. Ta funkcja zapewnia zaawansowane opcje dostosowywania rozmieszczenia tekstu i obrazów.

Czy biblioteka PDF Python obsługuje kompatybilność międzyplatformową?

IronPDF został zaprojektowany z myślą o kompatybilności międzyplatformowej, co gwarantuje, że generowane pliki PDF można wyświetlać i obsługiwać w spójny sposób na różnych systemach operacyjnych.

Dlaczego podczas generowania plików PDF w języku Python stosuje się kodowanie base64 dla obrazów?

Kodowanie Base64 służy do konwersji binarnych danych obrazu do formatu ciągu znaków, który można bezpośrednio osadzić w kodzie HTML. Dzięki temu obrazy można dołączać do pliku PDF bez konieczności odwoływania się do plików zewnętrznych.

Jakie są kluczowe funkcje IronPDF for Python?

IronPDF oferuje takie funkcje, jak łatwa integracja ze środowiskami Python, obsługa tekstu sformatowanego i obrazów oraz kompatybilność międzyplatformowa. Cechy te sprawiają, że jest to wszechstronne narzędzie do generowania plików PDF z dynamiczną treścią.

W jaki sposób IronPDF może pomóc w generowaniu dynamicznych dokumentów PDF?

IronPDF zapewnia potężny interfejs API, który pozwala programistom generować pliki PDF z dynamiczną treścią, taką jak tekst i obrazy. Obsługuje HTML i CSS do formatowania, co ułatwia tworzenie atrakcyjnych wizualnie dokumentów w języku Python.

Curtis Chau
Autor tekstów technicznych

Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podrę...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie