简体   繁体   English

使用Python创建和写入pdf文件

[英]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. 代码工作正常,但无法打开.pdf文件。 What's the difference between a normal text file and pdf? 普通文本文件和pdf有什么区别? What to do if I want to create and write to a pdf file in python? 如果我想在python中创建和写入pdf文件该怎么办?

you could install the fpdf library and then: 你可以安装fpdf库,然后:

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? 普通文本文件和pdf有什么区别?

A PDF file has a specific format. PDF文件具有特定格式。 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. 文本是一个更简单的文件,因此当您尝试打开一个认为它是PDF但没有此格式的文件时,无法打开该文件。

What to do if I want to create and write to a pdf file in python? 如果我想在python中创建和写入pdf文件该怎么办?

You need to use a module, like PyPDF2 , Reportlab or FPDF . 您需要使用模块,如PyPDF2ReportlabFPDF Moreover read Python PDF library . 另外阅读Python PDF库

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. 通常文件扩展名(在这种情况下为“.pdf”)设置为告诉您文件使用的内部格式,但并不能绝对保证。

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. 如果使用Python将字符串写入文件,则该文件将具有您放入其中的文件,在这种情况下,只有五个ASCII字符H,e,l,l和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. 因此,在这种情况下,您已创建了一个文本文件,但在其上放置了“.pdf”扩展名。 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). 它的内部格式仍然是一个文本文件,如果你将它重命名为'file.txt',你会发现你可以打开它(使用文本编辑器)。

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. 如果要创建真正的PDF文件(具有正确的PDF内部格式),则需要使用可以编写该类型文件的专用包。 @gsamaras and @rasmus-lyngdal-christensen gave some good suggestions (Reportlab, PyPDF2 and fpdf). @gsamaras和@ rasmus-lyngdal-christensen给出了一些很好的建议(Reportlab,PyPDF2和fpdf)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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