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

Patricia Arquette
풀어 주다: 2024-10-22 14:56:02
원래의
701명이 탐색했습니다.

How to Add Text to Existing PDFs Using Python?

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

배경:

기존 PDF 문서에 추가 텍스트를 추가해야 하는 경우가 종종 있습니다. 다행히 Python은 이 작업을 단순화하는 여러 모듈을 제공합니다. 그러나 Windows 및 Linux 시스템 모두와 호환되는 모듈을 식별하는 것이 중요합니다.

권장 모듈:

다양한 옵션을 고려한 후 적합한 두 가지 모듈은 PyPDF2와 PyPDF. 이러한 모듈은 높은 수준의 기능과 크로스 플랫폼 지원을 제공합니다.

코드 예:

다음은 Python 2.7 및 Python 3에 대한 코드 예입니다. x:

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.addPage(page)
# Finally, write "output" to a real file
output_stream = open("destination.pdf", "wb")
output.write(output_stream)
output_stream.close()</code>
로그인 후 복사

이 코드 예제는 기존 PDF 파일의 첫 번째 페이지에 "Hello world"라는 텍스트를 추가하고 결과를 새 PDF 파일에 저장합니다. 이에 따라 텍스트와 위치를 맞춤설정할 수 있습니다.

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

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!