>  기사  >  백엔드 개발  >  Python에서 기존 PDF에 텍스트를 추가하는 방법: 단계별 가이드

Python에서 기존 PDF에 텍스트를 추가하는 방법: 단계별 가이드

Patricia Arquette
Patricia Arquette원래의
2024-10-22 14:26:03149검색

How to Add Text to Existing PDFs in Python: A Step-by-Step Guide

Python을 사용하여 기존 PDF에 텍스트 추가: 포괄적인 솔루션

소개:
기존 PDF에 텍스트 추가 Python의 PDF는 다양한 응용 프로그램에서 중요한 작업이 될 수 있습니다. 이 문서에서는 pyPdf 및 ReportLab을 포함한 Python 모듈 조합을 사용하여 이를 수행하는 방법에 대한 자세한 가이드를 제공합니다.

PDF 조작을 위한 Python 라이브러리:
시작하려면 다음 모듈:

  • pyPdf: PDF 읽기 및 쓰기용
  • ReportLab: PDF에 텍스트 및 그래픽 추가용

Python 2.7 예:
Python 2.7을 사용하여 기존 PDF에 텍스트를 추가하려면 다음 단계를 따르세요.

  1. 필요한 모듈 가져오기:

    <code class="python">from pyPdf import PdfFileWriter, PdfFileReader
    import StringIO
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import letter</code>
  2. ReportLab을 사용하여 추가하려는 텍스트가 포함된 새 PDF 만들기:

    <code class="python">packet = StringIO.StringIO()
    can = canvas.Canvas(packet, pagesize=letter)
    can.drawString(10, 100, "Hello world")
    can.save()</code>
  3. 새 PDF 작성기 만들기:

    <code class="python">output = PdfFileWriter()</code>
  4. 새 페이지를 기존 PDF와 병합:

    <code class="python">existing_pdf = PdfFileReader(file("original.pdf", "rb"))
    page = existing_pdf.getPage(0)
    page.mergePage(new_pdf.getPage(0))
    output.addPage(page)</code>
  5. 수정된 PDF 저장:

    <code class="python">outputStream = file("destination.pdf", "wb")
    output.write(outputStream)
    outputStream.close()</code>

Python 3.x 예:
Python 3.x의 경우 코드가 약간 다릅니다.

  1. 모듈 가져오기:

    <code class="python">from PyPDF2 import PdfFileWriter, PdfFileReader
    import io
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import letter</code>
  2. ReportLab을 사용하여 텍스트가 포함된 새 PDF 만들기:

    <code class="python">packet = io.BytesIO()
    can = canvas.Canvas(packet, pagesize=letter)
    can.drawString(10, 100, "Hello world")
    can.save()</code>
  3. 새 작성자 만들기:

    <code class="python">output = PdfFileWriter()</code>
  4. 병합 페이지:

    <code class="python">existing_pdf = PdfFileReader(open("original.pdf", "rb"))
    page = existing_pdf.pages[0]
    page.merge_page(new_pdf.pages[0])
    output.add_page(page)</code>
  5. 파일 저장:

    <code class="python">output_stream = open("destination.pdf", "wb")
    output.write(output_stream)
    output_stream.close()</code>

이 예제를 사용하면 텍스트나 기타 요소를 효과적으로 추가할 수 있습니다. Python과 적절한 라이브러리를 사용하여 기존 PDF에 추가합니다. 이는 다양한 사용 사례에 맞게 PDF 문서를 수정하고 향상시키는 강력한 도구를 제공합니다.

위 내용은 Python에서 기존 PDF에 텍스트를 추가하는 방법: 단계별 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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