Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
In this digital day and age, the need to generate PDF documents with dynamic content, including text and images, is a common requirement. Python is a popular programming language which makes it easy to automate routine processes to save time and energy. Having a versatile library to create PDF files with text and images in Python can be very handy for automatic generation of reports, receipts or invoices. IronPDF, a versatile Python library, simplifies the process of creating PDFs with rich content.
In this article, we will explore how to use IronPDF to generate PDFs that include both text and images in a Python project.
IronPDF is a feature-rich Python library that provides developers with powerful tools for creating, manipulating, and processing PDF documents. With IronPDF, you can easily incorporate text, images, tables, and other elements into your PDFs, making it a valuable asset for a wide range of applications, from report generation to document creation.
Key Features of IronPDF:
Before diving into the process to create PDF documents using IronPDF, ensure that you have the following prerequisites in place:
Once the prerequisites are met, open PyCharm and create a new Python project. Set up a virtual environment for your project to manage dependencies effectively.
Choose the project type. For a simple Python project, you can stick with the default settings.
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.
Let's walk through the steps to create a single PDF page document that includes both text and image using 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
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()
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 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>
"""
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.
with open("ironpdf-logo.png", "rb") as f:
pngBinaryData = f.read()
imgDataUri = "data:image/png;base64," + base64.b64encode(pngBinaryData).decode("utf-8")
imgHtml = f"""<!-- Embedded Image -->
<img src='{imgDataUri}' width=100px height=100px
alt="IronPDF Logo">
</section>
</body>
</html>
"""
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
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)
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")
Now after executing the program, the output PDF file is as follows:
Similarly, multiple PDF pages can be added to a PDF file with ease.
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 send as an optional argument to 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")
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 tag 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.
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.
You can download and install the library from IronPDF's website.
9 .NET API products for your office documents