>  기사  >  백엔드 개발  >  Python 및 외부 모듈을 사용하여 기존 PDF에 텍스트를 추가하는 방법은 무엇입니까?

Python 및 외부 모듈을 사용하여 기존 PDF에 텍스트를 추가하는 방법은 무엇입니까?

DDD
DDD원래의
2024-10-22 15:30:03254검색

How to add text to existing PDF using Python and External Modules?

Python을 사용하여 기존 PDF에 텍스트 추가

PDF 문서 작업을 하다 보면 텍스트를 추가해야 하는 경우가 종종 있습니다. 이는 간단한 주석부터 복잡한 워터마크까지 다양합니다. PDF 편집을 위한 기본 제공 Python 라이브러리가 없으므로 이 기능을 구현하려면 외부 모듈을 사용해야 합니다.

PyPDF 및 ReportLab

PyPDF 및 ReportLab은 Python에서 PDF를 조작하는 데 널리 사용되는 두 가지 옵션입니다. . 그러나 이들 모듈 중 어느 것도 기존 PDF 파일 편집을 직접 지원하지 않습니다. 주로 사용자 정의 콘텐츠가 포함된 새 PDF를 만드는 데 사용됩니다.

PyPDF와 ReportLab 결합

기존 PDF에 텍스트를 추가하려면 PyPDF와 ReportLab을 결합하여 사용할 수 있습니다. 다음은 Windows와 Linux 모두에서 작동하는 자세한 예입니다.

예제 코드:

Python 2.7:

<code class="python">from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(10, 100, "Hello world")
can.save()

# move to the beginning of the StringIO buffer
packet.seek(0)

# create a new PDF with Reportlab
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file("original.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = file("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()</code>

Python 3 .x:

<code class="python">from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = io.BytesIO()
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(10, 100, "Hello world")
can.save()

# move to the beginning of the StringIO buffer
packet.seek(0)

# create a new PDF with Reportlab
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(open("original.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.pages[0]
page.merge_page(new_pdf.pages[0])
output.add_page(page)
# finally, write "output" to a real file
output_stream = open("destination.pdf", "wb")
output.write(output_stream)
output_stream.close()</code>

이 솔루션은 워터마크 텍스트 생성을 위한 ReportLab의 유연성과 PyPDF의 페이지 조작 기능을 효과적으로 결합합니다.

위 내용은 Python 및 외부 모듈을 사용하여 기존 PDF에 텍스트를 추가하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.