Create PDF using Python

Native and high-performance PDF file creation without Adobe Acrobat installation using Python

How to generate PDF File via Python

To create a PDF, use Aspose.PDF for Python via .NET, a powerful and easy-to-use API. Open PyPI, search for aspose-pdf, and install it. Alternatively, run the command:

Console

pip install aspose-pdf

How to Create PDF using Python


It is easy for the developers to create, load, modify and convert PDF files directly from Python for .NET application in just a few lines of code.

  1. Include the namespace in your class file
  2. Initialize the Document class object.
  3. Add a page using Pages.Add() method.
  4. Create a new TextFragment object and set its text.
  5. Add TextFragment to the Paragraphs collection of the page.
  6. Save the PDF using Save(String) method.

Following source code shows how to create a PDF file using Python.

This sample code shows how to create PDF using Python

import aspose.pdf as apdf

from os import path
path_outfile = path.join(self.data_dir, outfile)

# Initialize document object
document = apdf.Document()
# Add page
page = document.pages.add()
# Add text to new page
textFragment = apdf.text.TextFragment("Hello, world!")
textFragment.position = apdf.text.Position(100, 600)

textFragment.text_state.font_size = 12
textFragment.text_state.font = apdf.text.FontRepository.find_font(
    "TimesNewRoman"
)
textFragment.text_state.background_color = apdf.Color.blue
textFragment.text_state.foreground_color = apdf.Color.yellow

# Create TextBuilder object
textBuilder = apdf.text.TextBuilder(page)

# Append the text fragment to the PDF page
textBuilder.append_text(textFragment)

document.save(path_outfile)