1. 程式人生 > >【Python程式設計】PDF檔案讀寫demo (mark)

【Python程式設計】PDF檔案讀寫demo (mark)

# pdf_demo.py
# coding: utf-8
# de8ug
# 需要提前安裝:pip install reportlab

from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
pdfmetrics.registerFont(TTFont('simsun', 'C:\WINDOWS\Fonts\simsun.ttc'
)) # 匯入字型檔案,使用Windows字型或下載好的"simsun.ttf",用來顯示中文 class ExportPDF: """ Export a pdf file based on reportlab 把要處理的文字result_list寫成pdf檔案 """ def __init__(self, result_list, output_path='out1.pdf', is_custom_color=False, color=(0.77, 0.77, 0.77), font_size=8, offset_x=5, offset_y=5): self.
result_list = result_list self.output_path = output_path self.is_custom_color = is_custom_color self.font_size = font_size self.offset_x = offset_x self.offset_y = offset_y def save_string(self): """使用canvas把資料繪製到pdf檔案,預設座標從左下角開始,與螢幕座標(右上角開始)相反,所以需要單獨處理 """
c = canvas.Canvas(self.output_path, pagesize=A4) width, height = A4 # 使用預設的A4大小 if self.is_custom_color: c.setFillColorRGB(color) # 需要單獨設定顏色時候使用 new_height = height for line in self.result_list: c.setFont("simsun", self.font_size) # 處理中文字型 # 寫入每一行的資料,每一行的y座標需要單獨處理,這裡用總高度減去偏移量和字型高度,使得每一行依次寫入檔案 new_height = new_height - self.offset_y - self.font_size print('write data: ', self.offset_x, new_height, line) c.drawString(self.offset_x, new_height, line) c.showPage() c.save() def save_text(self): """使用canvas把資料繪製到pdf檔案, 這是另一種寫法,通過文字的方式寫入,只需要定義原始寫入座標 """ c = canvas.Canvas(self.output_path, pagesize=A4) width, height = A4 # 使用預設的A4大小 if self.is_custom_color: c.setFillColorRGB(color) # 需要單獨設定顏色時候使用 c.setFont("simsun", self.font_size) # 處理中文字型 obj = c.beginText() # 生成text物件 obj.setTextOrigin(10, height-self.offset_y*20) # 第一次寫入位置,座標自定義,注意高度需要調整 for line in self.result_list: print('write data: ', line) obj.textLine(line) # 寫入檔案 c.drawText(obj) c.showPage() c.save() def main(): result_list = ['line1', 'line2', 'line3中文', 'line4繼續'] pdf = ExportPDF(result_list) # pdf.save_string() pdf.save_text() if __name__ == "__main__": main()