简体   繁体   中英

Creating and writing to a pdf file in Python

Why won't this work :

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

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

you could 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')

What's the difference between a normal text file and pdf?

A PDF file has a specific format. You can read more here . A text is a much simpler file, thus when you attempt to open a file that you think it's a PDF, but doesn't have this format, the file cannot be opened.

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

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

Every type of file has its own internal format - a set of rules about what has to go where to define the information it is meant to represent. Usually the file extension ('.pdf' in this case) is set to tell you what internal format a file uses, but there's no absolute guarantee of that.

If you write a string to a file with Python, the file will have exactly what you put in it, in this case just the five ASCII characters H, e, l, l and o. That would correspond to the normal format for a text file. So in this case, you have created a text file but put a '.pdf' extension on it. Its internal format is still a text file, and if you rename it to 'file.txt', you'll find you can open it just fine (with a text editor).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM