Javascript required
Skip to content Skip to sidebar Skip to footer

Python Read and Modify File Line by Line

In this Python tutorial, we volition learn how to Create and modify pdf file in Python, and also we volition cover these topics:

  • How to create a pdf file in python
  • Create pdf by taking size A4
  • Create pdf by taking size A5
  • Create a table in pdf using python
  • Create a table with the filigree in pdf using python
  • Python create pdf from images
  • How to rotate the pdf in python
  • How to create a pdf of days in a yr python
  • Python create pdf from HTML
  • Python creates a pdf from a text file
  • Python create pdf from images with each page having individual image sizes

PDF Portable Document Format

To create a pdf in Python, we can have different size of pages such as:

  • A4
  • A3
  • A5
  • letter
  • legal

How to create a pdf file in python

Now, we can run across how to create a pdf file in python.

  • In this example, I have imported a module chosen FPDF from fpdf. The fpdf is a library that is used to generate pdf documents in python.
  • To add the page, I have taken pdf.add_page() and to prepare the font pdf.set_font is used. Here, I have used Arial-blazon font and assigned size = 14.
  • The pdf.cell is used to print the prison cell with an optional edge and background.
  • The width = 200, elevation = 10, and txt = "welcome to PythonGuides", and length = ane and taken left alignment as marshal="L".
  • To generate the pdf file, I accept used pdf.output("python.pdf"). The python.pdf is the proper noun of the pdf with the extension.

Example:

          from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=14) pdf.jail cell(200, 10, txt="Welcome to PythonGuides", ln=1, marshal="L") pdf.output("python.pdf")        

Nosotros can run across the generated pdf file as the output. You tin refer to the below screenshot for the output.

How to create a pdf file in python
How to create a pdf file in python

This is how to create a pdf file in Python.

You lot may like Python concatenate list and Python string formatting with examples.

Create pdf by taking size A4 in Python

Now, we can meet how to create pdf by taking size A4 in python.

  • In this instance, I take imported a module called FPDF from fpdf and alleged a variable equally pdf and assigned orientation = 'p', where p as portrait and unit of measurement is taken to measure and the format every bit 'A4'.
  • The font is taken equally "Arial", and size=20 and cell are taken equally 200,x, and "Welcome to PythonGuides" is the text to write in the pdf file, the length is assigned every bit length=one, and alignment is set to left.
  • To generate the pdf file, I have used pdf.output("kushi.pdf"). The kushi is the name of the file along with the extension.

Example:

          from fpdf import FPDF pdf = FPDF(orientation='P', unit='mm', format='A4') pdf.add_page() pdf.set_font("Arial", size=20) pdf.prison cell(200, 10, txt="Welcome to PythonGuides", ln=1, align="L") pdf.output("kushi.pdf")        

Here, we can run across pdf generated with A4 format as the output. Yous can refer to the beneath screenshot for the output.

Create pdf by taking size A4
Create pdf by taking size A4

This is how to create pdf past taking size A4 in Python.

Read: PdfFileWriter Python Examples

Create pdf by taking size A5 in Python

Now, we can encounter how to create pdf by taking size A5 in python.

  • In this example, I accept imported a module called FPDF from fpdf and alleged a variable as pdf and assigned orientation = 'p', where p as portrait and unit is taken in mm and the format as 'A5'.
  • The font is taken as "Arial", and size=20 and jail cell are taken as 200,10, and "Welcome to PythonGuides" is the text to write in the pdf file. and length=1 and alignment is set to left.
  • To generate the pdf file, I accept used pdf.output("kushi.pdf"). kushi is the name of the file along with the extension.

Example:

          from fpdf import FPDF pdf = FPDF(orientation='P', unit='mm', format='A5') pdf.add_page() pdf.set_font("Arial", size=15) pdf.prison cell(200, x, txt="Welcome to PythonGuides", ln=one, marshal="L") pdf.output("kushi.pdf")        

Here, we can meet pdf generated with A5 format as the output. You tin can refer to the beneath screenshot for the output.

Create pdf by taking size A5

This is how to create pdf by taking size A5 in Python.

Y'all may like How to read video frames in Python?

Create a table in pdf using Python

Here, we tin can see how to Create a table in pdf using python.

  • In this example, I accept imported modules chosen colors from reportlab.lib and module A4 from reportlab.lib.pagesizes. and also imported modules like SimpleDocTemplate, Tabular array, TableStyle from reportlab.platypus.
  • The pdf.cell is used to print the jail cell with an optional border and background.
  • The variable called document is declared and assigned SimpleDocTemplate("tabular array.pdf", pagesize=A4),table.pdf is the proper name of the pdf file and page size as A4.
  • An empty variable is alleged every bit items and another variable is declared as data that contains some items in it.
  • To create a table, I have used t=Table(data) and to insert the items into the table items.append(t) is used.
  • The document.build(items) is used to automatically generate a pdf.

Instance:

          from reportlab.lib import colors from reportlab.lib.pagesizes import A4 from reportlab.platypus import SimpleDocTemplate, Table, TableStyle document = SimpleDocTemplate("table.pdf", pagesize=A4) items = [] data= [['Apple', 'Mango', 'Kiwi'], ['Tomato', 'Potato', 'Peas']] t=Table(data) items.append(t) document.build(items)        

The below screenshot shows the generated pdf with table without grid every bit the output.

Create a table in pdf using python
Create a tabular array in pdf using python

This is how to create a table in pdf using python.

Read, Extract text from PDF Python

Create a table with the grid in pdf using python

Here, we can encounter how to create a tabular array with the grid in pdf using python.

  • In this example, I take imported a module called colors from reportlab.lib and letter, inch from reportlab.lib.pagesizes.
  • The color module has some predefined basic colors that we can use.
  • The module SimpleDocTemplate, Table, TableStyle is imported from reportlab.platypus.
  • An empty variable is alleged as items and another variable is declared as data that contains some items in it.
  • To create a table, I accept used t=Table(data) and to insert the items into the table items.suspend(t) is used.
  • The indexing in Reportlab starts at(0, 0) for the kickoff row, first cavalcade.
  • Then (one, 1) simply applies the styling to everything below the kickoff row and right of the first column.
  • To get ii rows and 5 coloumns, I take used t=Table(data,5*[1*inch], 2*[i*inch]).
  • The manner of the table is given by alignments such as right and tiptop and also used VALIGN.
  • The INNERGRID is used to split the tabular array.
  • The items.append(t) is used to append the data into the table.
  • The document.build(items) is used to automatically generate a pdf.

Example:

          from reportlab.lib import colors from reportlab.lib.pagesizes import alphabetic character, inch from reportlab.platypus import SimpleDocTemplate, Table, TableStyle certificate = SimpleDocTemplate("tabular array.pdf", pagesize=alphabetic character) items = [] data= [['0', '2', 'four', '6', '8'], ['x', '12', 'fourteen', '16', '18']] t=Table(data,5*[1*inch], 2*[1*inch]) t.setStyle(TableStyle([('ALIGN',(i,1),(-2,-ii),'Right'), ('VALIGN',(-1,-1),(-1,-ane),'RIGHT'), ('ALIGN',(-1,-i),(-ane,-1),'RIGHT'), ('VALIGN',(-1,-1),(-ane,-1),'TOP'), ('INNERGRID', (0,0), (-i,-1), 1, colors.black), ('BOX', (0,0), (-one,-1), 0.25, colors.black),])) items.append(t) document.build(items)        

The below screenshot shows the output :

Create a table with the grid in pdf using python
Create a table with the grid in pdf using python

This is how to create a table with the grid in pdf using python.

Python create pdf from images

Here, nosotros tin see how to create pdf from images in python.

  • In this example, I have imported a module called img2pdf and module Prototype from PIL and also Os.
  • The variable is declared every bit imagepath and assigned the path of the image.
  • Here cartoon.pdf is the name of the pdf to be created.
  • To write the imagefile in the pdf f.write is used and and then to shut the file file.shut() is used.

Instance:

          import img2pdf  from PIL import Image  import os  imagepath = r"C:\Users\Administrator.SHAREPOINTSKY\Downloads\mickey.png" pdfname = "cartoon.pdf" image = Prototype.open(imagepath)  pdf_bytes = img2pdf.convert(image.filename)  file = open(pdfname, "wb")  file.write(pdf_bytes)  image.close()  file.shut()                  

We tin that the imagefile is in pdf format as the output. You can refer to the below screenshot for the output:

Python create pdf from images
Python create pdf from images

This is how to create pdf from images in Python.

How to rotate a pdf in Python

Now, we can run across how to rotate pdf in python.

  • In this instance, I take imported a module chosen pikepdf and to select the pdf, I have used pdf = pikepdf.Pdf.open('cartoon.pdf').
  • The cartoon.pdf is the name of the file for loop is used to rotate the pdf, I have used the page.Rotate = 180.
  • To save the new rotated pdf with another name to that file, I have used pdf.salve('rotated.pdf') the rotated.pdf is the name of the new file.

Example:

          import pikepdf pdf = pikepdf.Pdf.open('drawing.pdf') for page in pdf.pages:    folio.Rotate = 180 pdf.save('rotated.pdf')        

The below screenshot shows the output:

How to rotate the pdf in python
How to rotate the pdf in python

This is how to rotate a pdf in Python.

How to create a pdf of days in a year python

Now, we can see How to create a pdf of days in a year in python.

  • In this example, I accept imported a module called inch from reportlablib, colors from reportlab.lib, and imported A4 from reportlab.lib.pagesizes.
  • The module SimpleDocTemplate, Tabular array, TableStyle is imported from reportlab.platypus.
  • The module Drawing is imported from reportlab.graphics.shapes.
  • To get the calendar in the pdf, I have imported a module called a calendar.
  • An empty variable is declared equally items and another variable is declared as information that contains some items in information technology.
  • To assign the days of the week, I take used cal = [['Mon', 'Tue', 'Midweek', 'Thu', 'Fri', 'Sat', 'Sunday']].
  • The .extend is used to add the elements to the tabular array.
  • To carve up the rows and coloumns of the table, I have used table = Table(cal, 7*[inch], len(cal) * [inch]).
  • I have used Helvetica font and alignment is taken according to the requirement and inner grid is colored with blue and the box is colored with the color red.
  • The document.build(items) is used to automatically generate a pdf.

Example:

          from reportlab.lib.units import inch from reportlab.lib import colors from reportlab.lib.pagesizes import A4 from reportlab.platypus import SimpleDocTemplate, Tabular array, TableStyle from reportlab.graphics.shapes import Cartoon import calendar doc = SimpleDocTemplate('cal.pdf', pagesize=A4) items = [] cal = [['Monday', 'Tue', 'Wed', 'Thu', 'Friday', 'Sat', 'Sunday']] cal.extend(agenda.monthcalendar(2021,2)) table = Table(cal, 7*[inch], len(cal) * [inch]) table.setStyle(TableStyle([         ('FONT', (0, 0), (-one, -i), 'Helvetica'),         ('FONT', (0, 0), (-ane, 0), 'Helvetica-Bold'),         ('FONTSIZE', (0, 0), (-1, -1), 8),         ('INNERGRID', (0, 0), (-1, -i), 0.5, colors.blue),         ('BOX', (0, 0), (-one, -1), 0.5, colors.ruddy),         ('ALIGN', (0, 0), (-one, -1), 'Center'),         ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),     ])) items.suspend(table) doc.build([table])        

The beneath screenshot shows the calender in the pdf as the output.

How to create a pdf of days in a year python
How to create a pdf of days in a twelvemonth python

This is how to create a pdf of days in a year in Python.

Python create pdf from HTML

  • Firstly, we have to install pdfkit by using pip install pdfkit.
  • We accept to download wkhtmltopdf by using the link: WKHTMLTOPDF
  • Later on downloading we have to copy the path of wkhtmltopdf file and paste it into the environmental variable.

Here, we can encounter how to create pdf from HTML in python.

  • In this example, I take imported a module called pdfkit.
  • The path of the file is assigned along with .exe. The variable config is defined and pdfkit.configuration() is assigned, this takes the configuration options equally the initial parameter
  • To convert the html file to pdf, I accept used pdfkit.from_file('kavita.html', 'newfile.pdf', configuration=config.
  • The kavita.html is the proper name of the Html file and newfile is the generated pdf file.

Case:

          import pdfkit path_wkhtmltopdf = r'C:/Users/Administrator.SHAREPOINTSKY/Desktop/Work/wkhtmltopdf/bin/wkhtmltopdf.exe' config = pdfkit.configuration(wkhtmltopdf=path_wkhtmltopdf) pdfkit.from_file('kavita.html', 'newfile.pdf', configuration=config)        

We can encounter the generated new pdf as the output. Yous can refer to the beneath screenshot for the output.

Python create pdf from HTML
Python create pdf from HTML

This is how we can create a pdf from HTML in Python.

Python create a pdf from a text file

Here, we cam see how to create a pdf from text file in python.

  • In this instance, I have imported a module called FPDP from fpdf. This is a library used to generate pdf documents.
  • To add the folio, I have used pdf.add_page() to set the font "Arial" and size = 15 is assigned.
  • To open the file, I have assigned the path of the file and "r" used to read the file.
  • The for loop is used, the size of the prison cell is given as pdf.cell(200, 10, txt = ten, ln = five, align = '50') and alignment equally left.
  • To get the generated pdf, I have used pdf.output("textfile.pdf").

Example:

          from fpdf import FPDF  pdf = FPDF()     pdf.add_page()  pdf.set_font("Arial", size = 15)  f = open(r"C:\Users\Ambassador.SHAREPOINTSKY\Desktop\Work\my_file.txt", "r")  for 10 in f:      pdf.jail cell(200, x, txt = x, ln = 5, marshal = '50')  pdf.output("textfile.pdf")                  

The below screenshot shows the generated pdf every bit the output:

python create a pdf text file
python create a pdf text file

This is how we tin can create a pdf from a text file in Python.

Python create pdf from images with each page having individual epitome sizes

Here, nosotros tin can run across how to create pdf from images with each page having individual image sizes in python.

  • Here, I accept imported a module chosen Epitome from PIL and as well imported img2pdf and to open the file, I take used with open( 'cartoonsize.pdf', 'wb' ) equally f, and 'wb' fashion is used to write the file in binary fashion.
  • The size of the page is assigned as an epitome.width, l and image.superlative,50. The FitMode is used to fill up the exact shrink overstate.
  • To write the prototype into the pdf f.write is used to convert the image to pdf and the path of the file is assigned.
  • We can see the number of pages in the corner of the pdf.

Example:

          from PIL import Epitome import img2pdf with open( 'cartoonsize.pdf', 'wb' ) equally f:     image = Paradigm.open up( r'C:\Users\Administrator.SHAREPOINTSKY\doll.jpg' )     my_layout_fun = img2pdf.get_layout_fun(         pagesize = ( img2pdf.px_to_pt( image.width, fifty ), img2pdf.px_to_pt( image.acme, 50) ),         fit = img2pdf.FitMode.into      )     f.write( img2pdf.convert( [r'C:\Users\Ambassador.SHAREPOINTSKY\doll.jpg', r'C:\Users\Ambassador.SHAREPOINTSKY\Desktop\Work\cat.jpg'], layout_fun = my_layout_fun ))        

Here, we can come across 2 pages of pdf that contain images with sizes assigned to them as the output. Yous can refer to the below screenshot for the output:

Python create pdf from images with each page having individual image sizes
Python create pdf from images with each page having individual epitome sizes

You may similar the following Python tutorials:

  • Create a game using Python Pygame (Tic tac toe game)
  • Python Pandas CSV Tutorial
  • How to Convert DateTime to UNIX timestamp in Python
  • Python catch multiple exceptions
  • Python Pygame tutorial
  • Python Cord Functions
  • Python naming conventions
  • Python intersection of sets

In this tutorial, we have learned well-nigh Create and modify pdf file in python, and also we have covered these topics:

  • How to create a pdf file in python
  • Create pdf by taking size A4
  • Create pdf by taking size A5
  • Create a table in pdf using python
  • Create a table with the grid in pdf using python
  • Python create pdf from images
  • How to rotate the pdf in python
  • How to create a pdf of days in a year python
  • Python create pdf from HTML
  • Python creates a pdf from a text file
  • Python create pdf from images with each page having individual image sizes

Python Read and Modify File Line by Line

Source: https://pythonguides.com/create-and-modify-pdf-file-in-python/