PDFの上に画像を配置する 質問する

PDFの上に画像を配置する 質問する

既存の PDF ファイルの特定の座標位置に画像を配置するにはどうすればよいでしょうか。PDF は 1 ページの図面シートを表します。画像は拡大縮小されます。ReportLab を確認していますが、答えが見つかりません。よろしくお願いします。

ベストアンサー1

5 年が経過しました。これらの回答には細心の注意が必要だと思います。ここに完全な解決策があります。

以下はPython 2.7でテストされています

依存関係をインストールする

pip install reportlab 
pip install pypdf2

魔法をかける

from reportlab.pdfgen import canvas
from PyPDF2 import PdfFileWriter, PdfFileReader

# Create the watermark from an image
c = canvas.Canvas('watermark.pdf')

# Draw the image at x, y. I positioned the x,y to be where i like here
c.drawImage('test.png', 15, 720)

# Add some custom text for good measure
c.drawString(15, 720,"Hello World")
c.save()

# Get the watermark file you just created
watermark = PdfFileReader(open("watermark.pdf", "rb"))

# Get our files ready
output_file = PdfFileWriter()
input_file = PdfFileReader(open("test2.pdf", "rb"))

# Number of pages in input document
page_count = input_file.getNumPages()

# Go through all the input file pages to add a watermark to them
for page_number in range(page_count):
    print "Watermarking page {} of {}".format(page_number, page_count)
    # merge the watermark with the page
    input_page = input_file.getPage(page_number)
    input_page.mergePage(watermark.getPage(0))
    # add page from input file to output document
    output_file.addPage(input_page)
   
# finally, write "output" to document-output.pdf
with open("document-output.pdf", "wb") as outputStream:
    output_file.write(outputStream)

参考文献:

pypdf プロジェクトページ:https://pypi.org/project/pypdf/

Reportlab ドキュメント:http://www.reportlab.com/apis/reportlab/2.4/pdfgen.html

Reportlab 完全ユーザーガイド:https://www.reportlab.com/docs/reportlab-ユーザーガイド.pdf

おすすめ記事