如何用Python在PDF中添加垂直/旋转文本?PyFPDF等库实现方案咨询
Absolutely! You can absolutely add rotated or vertical text in your PDF using PyFPDF—turns out it does support this, even if it’s not immediately obvious. Let me walk you through a few approaches, plus alternatives if you need more flexibility.
PyFPDF has built-in support for rotating text via coordinate transformations. Here’s how to implement it:
1. Rotate Text at a Specific Position
Use the rotate() method to set a rotation angle, draw your text, then reset the rotation to avoid affecting subsequent content. This works perfectly for vertical text (rotated 90 or 270 degrees):
from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=12) # Rotate 90 degrees clockwise around (x=10, y=50) pdf.rotate(90, x=10, y=50) pdf.text(x=10, y=50, txt="Vertical Text (Rotated 90°)") pdf.rotate(0) # Reset rotation to default # Rotate -90 degrees (270° clockwise) for the opposite vertical direction pdf.rotate(-90, x=190, y=50) pdf.text(x=190, y=50, txt="Vertical Text (Rotated -90°)") pdf.rotate(0) # Add regular text for comparison pdf.text(x=50, y=50, txt="Regular Horizontal Text") pdf.output("rotated_text.pdf")
Note: The
rotate()method takes the rotation angle (in degrees) and the origin point (x, y) around which the text will rotate. Always reset the rotation to 0 after drawing your rotated text—otherwise all future content will inherit the rotation.
If you need more flexibility (like wrapped rotated text or complex layouts), these Python libraries are excellent options:
1. ReportLab
ReportLab is a robust PDF generation tool with intuitive rotated text support:
from reportlab.pdfgen import canvas c = canvas.Canvas("reportlab_rotated.pdf") c.setFont("Arial", 12) # Draw vertical text (90 degrees rotation) c.saveState() c.rotate(90) c.drawString(50, -100, "Vertical Text with ReportLab") c.restoreState() # Add regular horizontal text c.drawString(50, 100, "Regular Horizontal Text") c.save()
2. PyMuPDF (fitz)
PyMuPDF is great for both creating new PDFs and modifying existing ones, with straightforward rotated text insertion:
import fitz doc = fitz.open() page = doc.new_page() # Insert vertical text (90 degrees rotation) page.insert_text((10, 50), "Vertical Text with PyMuPDF", fontsize=12, rotate=90) # Insert regular text page.insert_text((50, 50), "Regular Horizontal Text", fontsize=12) doc.save("pymupdf_rotated.pdf")
You don’t need to switch to PHP’s FPDF—PyFPDF fully supports rotated/vertical text using its rotate() method. For more advanced use cases, ReportLab or PyMuPDF offer even more flexibility to handle complex text layouts.
内容的提问来源于stack exchange,提问作者Michael




