from pypdf import PdfReader, PdfWriter
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.colors import red,black
import io
import sys
def main():
org_pdf_path = sys.argv[1]
new_pdf_path = "new.pdf"
pdfmetrics.registerFont(TTFont("IPAexGothic", "./ipaexg.ttf"))
pdf_reader = PdfReader( open(org_pdf_path, "rb") )
pdf_writer = PdfWriter()
for page in pdf_reader.pages:
page = add_object_to_page(page)
pdf_writer.add_page(page)
with open(new_pdf_path, "wb") as output_file:
pdf_writer.write(output_file)
def add_object_to_page(page):
packet = io.BytesIO()
can = canvas.Canvas(packet,
pagesize=(page.mediabox.width,
page.mediabox.height))
tmp_txt = """
reportlab を用い、pdfへ図形や文字列を追加しています。
reportlab を用い、pdfへ図形や文字列を追加しています。
reportlab を用い、pdfへ図形や文字列を追加しています。
reportlab を用い、pdfへ図形や文字列を追加しています。
"""
can.setFont("IPAexGothic", 10)
can.setFillColor(red, alpha=0.4)
can.drawString(10, page.mediabox.height - 30, tmp_txt)
textobject = can.beginText(10, page.mediabox.height - 50)
textobject.setFont("IPAexGothic", 10)
textobject.textLines(tmp_txt)
can.drawText(textobject)
can.save()
packet.seek(0)
new_pdf = PdfReader(packet)
page.merge_page(new_pdf.pages[0] )
return page
if __name__ == "__main__":
main()