如何将python中的代码保存为PDF
时间: 2023-12-03 19:43:06 浏览: 32
你可以使用第三方库`reportlab`将Python代码保存为PDF。以下是保存Python代码为PDF的示例代码:
```python
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import PdfFormatter
def save_code_to_pdf(code, filename):
# Create a new PDF object
c = canvas.Canvas(filename, pagesize=letter)
# Set the font size and line width
c.setFont("Courier", 10)
c.setLineWidth(0.3)
# Highlight the code using Pygments
highlighted_code = highlight(code, PythonLexer(), PdfFormatter())
# Split the code into lines
lines = highlighted_code.split("\n")
# Loop through the lines and draw them on the PDF
y = 750
for line in lines:
c.drawString(50, y, line)
y -= 12
# Save the PDF
c.save()
# Example usage
code = """
def hello_world():
print("Hello, world!")
hello_world()
"""
save_code_to_pdf(code, "hello_world.pdf")
```
这个例子使用`reportlab`库创建一个新的PDF对象,然后使用`pygments`库对Python代码进行高亮处理,并将它们绘制到PDF中。最后,使用`c.save()`方法保存PDF文件。