푸터 콘텐츠로 바로가기
PYTHON PDF 도구

Python에서 PDF 파일을 만드는 방법

PDF (Portable Document Format) is the most popular digital file format for sending and receiving data online. It is mainly used to preserve the data formatting and secure the data with an encrypted password. The .pdf extension is independent of software applications, hardware, or operating systems.

In this article, we are going to create a PDF file in the Python programming language. There are a bunch of online options available but here we will use a Python library for creating PDF files. Following are the two famous libraries to generate PDF documents with single or multiple pages in Python:

  1. Reportlab
  2. PDFKit

From the above-mentioned PDF python libraries, we can use anyone to generate PDFs.

How to Create a PDF File in Python?

Let's have a look at both libraries one by one.

Creating PDF Files using Reportlab library

Reportlab library is a free open-source PDF toolkit that can be used to easily create PDF files. It provides a bunch of drawing tools for adding images and text at a certain position on multiple pages. You can also create encrypted PDF files using the encryptCanvas method.

Installation

To install Reportlab, the pip package manager is required. It automatically downloads and installs the requested package using the pip command. Simply type the following command in Windows cmd or PowerShell:

pip install reportlab
pip install reportlab
SHELL

Note: While installing Python, it must be added to the path environment variable in order to execute the above command from anywhere in cmd or PowerShell. Pip is recommended to be used for Python 3+, as it is the updated version.

Open a New Python File

To use the Reportlab library, we need to write the code in a Python file and execute it to create PDF files.

  1. Search and open Python default IDLE shell from the Windows search bar and press Ctrl + N or select "New File" from the File tab. This will open the text editor for writing the code.
  2. Next, save the file with the appropriate name. I'm naming it "createpdf.py".

Python Code for Creating PDF

The following code will draw document elements and generate a PDF within seconds:

# Importing required modules from ReportLab
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors

# File and document attributes
fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'

# Creating a PDF object
pdf = canvas.Canvas(fileName)

# Setting the title of the document
pdf.setTitle(documentTitle)

# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))

# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)

# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255)  # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)

# Saving the PDF
pdf.save()
# Importing required modules from ReportLab
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
from reportlab.lib import colors

# File and document attributes
fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'

# Creating a PDF object
pdf = canvas.Canvas(fileName)

# Setting the title of the document
pdf.setTitle(documentTitle)

# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))

# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)

# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255)  # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)

# Saving the PDF
pdf.save()
PYTHON

Code Explanation

After importing all the modules and packages, we first initialized all the content which will be written to a PDF file.

fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'
fileName = 'sample.pdf'
documentTitle = 'sample'
title = 'Create PDF'
subTitle = 'Using ReportLab !!'
PYTHON

Now, we create the PDF canvas, set the document title, and then add a centered title and subtitle on the canvas with appropriate fonts and sizes.

# Creating a PDF object
pdf = canvas.Canvas(fileName)

# Setting the title of the document
pdf.setTitle(documentTitle)

# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))

# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)

# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255)  # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)
# Creating a PDF object
pdf = canvas.Canvas(fileName)

# Setting the title of the document
pdf.setTitle(documentTitle)

# Registering a TrueType font
pdfmetrics.registerFont(TTFont('abc', 'Arial.ttf'))

# Creating the title by setting its font and placing it on the canvas
pdf.setFont('abc', 36)
pdf.drawCentredString(300, 770, title)

# Creating the subtitle by setting its font, color, and placing it on the canvas
pdf.setFillColorRGB(0, 0, 255)  # Set color to blue
pdf.setFont("Courier-Bold", 24)
pdf.drawCentredString(290, 720, subTitle)
PYTHON

Finally, we save the PDF file when everything is drawn on the canvas.

# Saving the PDF
pdf.save()
# Saving the PDF
pdf.save()
PYTHON

We can also use drawString and drawText methods to create a simple PDF file using Reportlab in Python.

Create PDF files using PDFKit Library

PDFKit library is one of the best approaches when it comes to creating PDF files in Python. It can create PDF files using HTML code. You can render simple and complex HTML files or HTML from URLs to a pixel-perfect printable PDF page. However, PDFKit integrates wkhtmltopdf features to convert HTML to PDF. To install wkhtmltopdf for Windows, Linux, and Mac, visit this link.

Note: In Windows OS, wkhtmltopdf will be installed in program files.

Installation

Use the following command to install PDFKit:

pip install pdfkit
pip install pdfkit
SHELL

Creating PDF Files From URL

Creating PDF files using PDFKit is very simple and a one-line process.

import pdfkit

# Convert a webpage from a URL to a PDF file
pdfkit.from_url('http://google.com', 'out.pdf')
import pdfkit

# Convert a webpage from a URL to a PDF file
pdfkit.from_url('http://google.com', 'out.pdf')
PYTHON

Creating PDF Files From HTML Files

import pdfkit

# Convert an HTML file to a PDF file
pdfkit.from_file('index.html', 'out.pdf')
import pdfkit

# Convert an HTML file to a PDF file
pdfkit.from_file('index.html', 'out.pdf')
PYTHON

Creating PDF Files From HTML Templates

You can pass HTML templates as a string to convert them to a PDF as an output file.

import pdfkit

# HTML content to convert to PDF
html_string = """
    <html>
        <head>
        <meta name="pdfkit-page-size" content="Legal"/>
        <meta name="pdfkit-orientation" content="Landscape"/>
        </head>
        <body>Hello World!</body>
    </html>
    """

# Convert HTML string to a PDF file
pdfkit.from_string(html_string, 'out.pdf')
import pdfkit

# HTML content to convert to PDF
html_string = """
    <html>
        <head>
        <meta name="pdfkit-page-size" content="Legal"/>
        <meta name="pdfkit-orientation" content="Landscape"/>
        </head>
        <body>Hello World!</body>
    </html>
    """

# Convert HTML string to a PDF file
pdfkit.from_string(html_string, 'out.pdf')
PYTHON

PDFKit allows you to easily create PDFs in Python using HTML templates.

The IronPDF Library

IronPDF is a useful tool to create PDF files in .NET projects. A common use of this library is "HTML to PDF" rendering, where HTML is used as the design language for rendering a PDF document.

IronPDF uses a .NET Chromium engine to render HTML pages to PDF files. With HTML to PDF conversion, there is no need to use complex APIs to position or design PDFs. IronPDF also supports all standard web page technologies: HTML, ASPX, JS, CSS, and images.

It also enables you to create a .NET PDF library using HTML5, CSS, JavaScript, and images. You can edit, stamp, and add headers and footers to a PDF effortlessly. Furthermore, it makes it very easy to read PDF text and extract images.

To get started with IronPDF, you need to install the NuGet package (ensure this step is authenticated or run in a .NET development environment):

 pip install ironpdf

The following example helps you create a PDF directly from a URL:

from ironpdf import ChromePdfRenderer

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from a URL
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/")

# Export to a file
pdf.SaveAs("url.pdf")
from ironpdf import ChromePdfRenderer

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from a URL
pdf = renderer.RenderUrlAsPdf("https://ironpdf.com/")

# Export to a file
pdf.SaveAs("url.pdf")
PYTHON

The following code will help you create a PDF file from HTML code along with any CSS or JavaScript:

from ironpdf import ChromePdfRenderer

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from an HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")

# Export to a file
pdf.SaveAs("output.pdf")

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

# Instantiate Renderer
renderer = ChromePdfRenderer()

# Create a PDF from an HTML string using Python
pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")

# Export to a file
pdf.SaveAs("output.pdf")

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

You can see from the above code that it's quite simple and clean. Very few lines of code are needed to create a PDF file from HTML code. It's a fast, reliable, and time-saving solution with accurate results.

Download IronPDF and try it for free. After the trial period, licensing starts at $799.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.