Create and write to a PDF file in Python

Why this work will not:

with open('file.pdf', 'w') as outfile: outfile.write("Hello") 

The code works fine, but the .pdf file cannot be opened. What is the difference between a plain text file and pdf? What if I want to create and write a pdf file in python?

+8
source share
4 answers

you can install the fpdf library and then:

 from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_xy(0, 0) pdf.set_font('arial', 'B', 13.0) pdf.cell(ln=0, h=5.0, align='L', w=0, txt="Hello", border=0) pdf.output('test.pdf', 'F') 
+13
source

What is the difference between a plain text file and pdf?

PDF file has a specific format. You can read it here . Text is a much simpler file, so when you try to open a file that you think is a PDF file but does not have this format, the file cannot be opened.

What if I want to create and write a pdf file in python?

You need to use a module like PyPDF2 , Reportlab or FPDF . Moreover, read the Python PDF library .

+6
source

Each type of file has its own internal format - a set of rules about what it takes to determine what information it should represent. Usually the file extension (.pdf) in this case is set to indicate which internal format the file uses, but there is no absolute guarantee of this.

If you write a line to a file with Python, the file will have exactly what you put in it, in this case only five ASCII characters H, e, l, l and o. This will correspond to the normal text file format. Thus, in this case, you created a text file, but added the .pdf extension on it. Its internal format is still a text file, and if you rename it to file.txt, you will find that you can simply open it (using a text editor).

If you want to create a real PDF file (something with the correct internal format for PDF), you will need to use a specialized package that can write this type of file. @gsamaras and @ rasmus-lyngdal-christensen made some good suggestions (Reportlab, PyPDF2 and fpdf).

+2
source

I need to open a PDF file and put a circular annotation and text annotation in it with an increase in the number (page numbers), how will I go? Found two libraries pypdf2 and reportlab, but when I did this, I gave only 1 sheet, not an annotation.

0
source

Source: https://habr.com/ru/post/1271357/


All Articles