Konvertieren Sie Bilder mit Python in PDF
Inhaltsverzeichnis
- PDF-Konverter-API für Python
- Schritte zum Konvertieren eines Bildes in PDF
- Konvertieren Sie ein Bild in ein PDF-Dokument
- Konvertieren Sie mehrere Bilder in ein PDF-Dokument
- Erstellen Sie ein PDF aus mehreren Bildern und passen Sie die Seitenränder an
- Erstellen Sie ein PDF mit mehreren Bildern pro Seite
- Abschluss
- Siehe auch
Mit Pip installieren
pip install Spire.PDF
verwandte Links
Das Konvertieren eines Bildes in PDF ist eine bequeme und effiziente Möglichkeit, eine visuelle Datei in ein tragbares, allgemein lesbares Format umzuwandeln. Unabhängig davon, ob Sie mit einem gescannten Dokument, einem Foto oder einem digitalen Bild arbeiten, bietet die Konvertierung in PDF zahlreiche Vorteile. Es behält die Originalqualität des Bildes bei und gewährleistet die Kompatibilität mit verschiedenen Geräten und Betriebssystemen. Darüber hinaus ermöglicht die Konvertierung von Bildern in PDF ein einfaches Teilen, Drucken und Archivieren, was es zu einer vielseitigen Lösung für verschiedene berufliche, pädagogische und persönliche Zwecke macht. Dieser Artikel enthält mehrere Beispiele, die Ihnen zeigen, wie das geht Konvertieren Sie Bilder mit Python in PDF.
- Konvertieren Sie ein Bild in ein PDF-Dokument in Python
- Konvertieren Sie mehrere Bilder in ein PDF-Dokument in Python
- Erstellen Sie eine PDF-Datei aus mehreren Bildern und passen Sie die Seitenränder in Python an
- Erstellen Sie in Python ein PDF mit mehreren Bildern pro Seite
PDF-Konverter-API für Python
Wenn Sie Bilddateien in einer Python-Anwendung in das PDF-Format umwandeln möchten, kannSpire.PDF for Python dabei helfen. Sie können damit ein PDF-Dokument mit benutzerdefinierten Seiteneinstellungen (Größe und Ränder) erstellen, jeder einzelnen Seite ein oder mehrere Bilder hinzufügen und das endgültige Dokument als PDF-Datei speichern. Es werden verschiedene Bildformate unterstützt, darunter PNG-, JPEG-, BMP- und GIF-Bilder.
Zusätzlich zur Konvertierung von Bildern in PDF unterstützt diese Bibliothek die Konvertierung von PDF in Word, PDF in Excel, PDF in HTML, und PDF in PDF/A mit hoher Qualität und Präzision. Als erweiterte Python-PDF-Bibliothek bietet sie außerdem eine umfangreiche API für Entwickler, mit der sie die Konvertierungsoptionen anpassen können, um eine Vielzahl von Konvertierungsanforderungen zu erfüllen.
Sie können es installieren, indem Sie den folgenden pip-Befehl ausführen.
pip install Spire.PDF
Schritte zum Konvertieren eines Bilds in PDF in Python
- Initialisieren Sie die PdfDocument-Klasse.
- Laden Sie eine Bilddatei aus dem Pfad mit der FromFile-Methode.
- Fügen Sie dem Dokument eine Seite mit der angegebenen Größe hinzu.
- Zeichnen Sie das Bild mit der DrawImage-Methode an der angegebenen Stelle auf die Seite.
- Speichern Sie das Dokument mit der SaveToFile-Methode in einer PDF-Datei.
Konvertieren Sie ein Bild in ein PDF-Dokument in Python
Dieses Codebeispiel konvertiert eine Bilddatei mithilfe der Bibliothek Spire.PDF for Python in ein PDF-Dokument, indem ein leeres Dokument erstellt, eine Seite mit den gleichen Abmessungen wie das Bild hinzugefügt und das Bild auf die Seite gezeichnet wird.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
doc = PdfDocument()
# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)
# Load a particular image
image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\Images\\img-1.jpg")
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Add a page that has the same size as the image
page = doc.Pages.Add(SizeF(width, height))
# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile("output/ImageToPdf.pdf")
doc.Dispose()

Konvertieren Sie mehrere Bilder in ein PDF-Dokument in Python
Dieses Beispiel veranschaulicht, wie Sie mit Spire.PDF for Python eine Sammlung von Bildern in ein PDF-Dokument konvertieren. Der folgende Codeausschnitt liest Bilder aus einem angegebenen Ordner, erstellt ein PDF-Dokument, fügt jedes Bild einer separaten Seite im PDF hinzu und speichert die resultierende PDF-Datei.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for file in files:
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, file))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Add a page that has the same size as the image
page = doc.Pages.Add(SizeF(width, height))
# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile('output/ImagesToPdf.pdf')
doc.Dispose()

Erstellen Sie eine PDF-Datei aus mehreren Bildern und passen Sie die Seitenränder in Python an
Dieses Codebeispiel erstellt ein PDF-Dokument und füllt es mit Bildern aus einem angegebenen Ordner, passt die Seitenränder an und speichert das resultierende Dokument in einer Datei.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the left, top, right, bottom page margin
doc.PageSettings.SetMargins(30.0, 30.0, 30.0, 30.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for file in files:
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, file))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Specify page size
size = SizeF(width + doc.PageSettings.Margins.Left + doc.PageSettings.Margins.Right, height + doc.PageSettings.Margins.Top+ doc.PageSettings.Margins.Bottom)
# Add a page with the specified size
page = doc.Pages.Add(size)
# Draw image on the page at (0, 0)
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile('output/CustomizeMargins.pdf')
doc.Dispose()

Erstellen Sie in Python ein PDF mit mehreren Bildern pro Seite
Dieser Code zeigt, wie Sie mit der Spire.PDF-Bibliothek in Python ein PDF-Dokument mit zwei Bildern pro Seite erstellen. Die Bilder in diesem Beispiel haben die gleiche Größe. Wenn Ihre Bildgröße nicht konsistent ist, müssen Sie den Code anpassen, um das gewünschte Ergebnis zu erzielen.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the left, top, right, bottom page margins
doc.PageSettings.SetMargins(15.0, 15.0, 15.0, 15.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for i in range(len(files)):
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, files[i]))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Specify page size
size = SizeF(width + doc.PageSettings.Margins.Left + doc.PageSettings.Margins.Right, height*2 + doc.PageSettings.Margins.Top+ doc.PageSettings.Margins.Bottom + 15.0)
if i % 2 == 0:
# Add a page with the specified size
page = doc.Pages.Add(size)
# Draw first image on the page at (0, 0)
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
else :
# Draw second image on the page at (0, height + 15)
page.Canvas.DrawImage(image, 0.0, height + 15.0, width, height)
# Save to file
doc.SaveToFile('output/SeveralImagesPerPage.pdf')
doc.Dispose()

Abschluss
In diesem Blogbeitrag haben wir untersucht, wie Sie mit Spire.PDF for python PDF-Dokumente aus Bildern erstellen können, die ein oder mehrere Bilder pro Seite enthalten. Darüber hinaus haben wir gezeigt, wie Sie die PDF-Seitengröße und die Ränder um die Bilder anpassen können. Weitere Tutorials finden Sie in unserer Online-Dokumentation. Wenn Sie Fragen haben, können Sie uns gerne per E-Mail oder im Forum kontaktieren.
Convertir imagen a PDF con Python
Tabla de contenido
- API de conversión de PDF para Python
- Pasos para convertir una imagen a PDF
- Convertir una imagen a un documento PDF
- Convertir varias imágenes a un documento PDF
- Cree un PDF a partir de varias imágenes personalizando los márgenes de la página
- Cree un PDF con varias imágenes por página
- Conclusión
- Ver también
Instalar con Pip
pip install Spire.PDF
enlaces relacionados
Convertir una imagen a PDF es una forma cómoda y eficaz de transformar un archivo visual en un formato portátil y de lectura universal. Ya sea que esté trabajando con un documento escaneado, una fotografía o una imagen digital, convertirlo a PDF ofrece numerosos beneficios. Mantiene la calidad original de la imagen y garantiza la compatibilidad entre diversos dispositivos y sistemas operativos. Además, convertir imágenes a PDF permite compartirlas, imprimirlas y archivarlas fácilmente, lo que la convierte en una solución versátil para diversos fines profesionales, educativos y personales. Este artículo proporciona varios ejemplos que le muestran cómo convertir imágenes a PDF usando Python.
- Convertir una imagen en un documento PDF en Python
- Convierta varias imágenes a un documento PDF en Python
- Cree un PDF a partir de varias imágenes personalizando los márgenes de página en Python
- Cree un PDF con varias imágenes por página en Python
API de conversión de PDF para Python
Si desea convertir archivos de imagen a formato PDF en una aplicación Python, Spire.PDF for Python puede ayudarle con esto. Le permite crear un documento PDF con configuraciones de página personalizadas (tamaño y márgenes), agregar una o más imágenes a cada página y guardar el documento final como un archivo PDF. Se admiten varios formatos de imágenes que incluyen imágenes PNG, JPEG, BMP y GIF.
Además de la conversión de imágenes a PDF, esta biblioteca admite la conversión de PDF a Word, PDF a Excel, PDF a HTML, PDF a PDF/A con alta calidad y precisión. Como biblioteca PDF de Python avanzada, también proporciona una API enriquecida para que los desarrolladores personalicen las opciones de conversión para cumplir con una variedad de requisitos de conversión.
Puede instalarlo ejecutando el siguiente comando pip.
pip install Spire.PDF
Pasos para convertir una imagen a PDF en Python
- Inicialice la clase PdfDocument.
- Cargue un archivo de imagen desde la ruta usando el método FromFile.
- Agregue una página con el tamaño especificado al documento.
- Dibuja la imagen en la página en la ubicación especificada usando el método DrawImage.
- Guarde el documento en un archivo PDF utilizando el método SaveToFile.
Convertir una imagen en un documento PDF en Python
Este ejemplo de código convierte un archivo de imagen en un documento PDF usando la biblioteca Spire.PDF for Python creando un documento en blanco, agregando una página con las mismas dimensiones que la imagen y dibujando la imagen en la página.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
doc = PdfDocument()
# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)
# Load a particular image
image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\Images\\img-1.jpg")
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Add a page that has the same size as the image
page = doc.Pages.Add(SizeF(width, height))
# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile("output/ImageToPdf.pdf")
doc.Dispose()

Convierta varias imágenes a un documento PDF en Python
Este ejemplo ilustra cómo convertir una colección de imágenes en un documento PDF usando Spire.PDF for Python. El siguiente fragmento de código lee imágenes de una carpeta específica, crea un documento PDF, agrega cada imagen a una página separada en el PDF y guarda el archivo PDF resultante.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for file in files:
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, file))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Add a page that has the same size as the image
page = doc.Pages.Add(SizeF(width, height))
# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile('output/ImagesToPdf.pdf')
doc.Dispose()

Cree un PDF a partir de varias imágenes personalizando los márgenes de página en Python
Este ejemplo de código crea un documento PDF y lo completa con imágenes de una carpeta específica, ajusta los márgenes de la página y guarda el documento resultante en un archivo.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the left, top, right, bottom page margin
doc.PageSettings.SetMargins(30.0, 30.0, 30.0, 30.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for file in files:
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, file))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Specify page size
size = SizeF(width + doc.PageSettings.Margins.Left + doc.PageSettings.Margins.Right, height + doc.PageSettings.Margins.Top+ doc.PageSettings.Margins.Bottom)
# Add a page with the specified size
page = doc.Pages.Add(size)
# Draw image on the page at (0, 0)
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile('output/CustomizeMargins.pdf')
doc.Dispose()

Cree un PDF con varias imágenes por página en Python
Este código demuestra cómo utilizar la biblioteca Spire.PDF en Python para crear un documento PDF con dos imágenes por página. Las imágenes en este ejemplo tienen el mismo tamaño; si el tamaño de su imagen no es consistente, entonces deberá ajustar el código para lograr el resultado deseado.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the left, top, right, bottom page margins
doc.PageSettings.SetMargins(15.0, 15.0, 15.0, 15.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for i in range(len(files)):
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, files[i]))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Specify page size
size = SizeF(width + doc.PageSettings.Margins.Left + doc.PageSettings.Margins.Right, height*2 + doc.PageSettings.Margins.Top+ doc.PageSettings.Margins.Bottom + 15.0)
if i % 2 == 0:
# Add a page with the specified size
page = doc.Pages.Add(size)
# Draw first image on the page at (0, 0)
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
else :
# Draw second image on the page at (0, height + 15)
page.Canvas.DrawImage(image, 0.0, height + 15.0, width, height)
# Save to file
doc.SaveToFile('output/SeveralImagesPerPage.pdf')
doc.Dispose()

Conclusión
En esta publicación de blog, exploramos cómo usar Spire.PDF for Python para crear documentos PDF a partir de imágenes, que contienen una o más imágenes por página. Además, demostramos cómo personalizar el tamaño de la página PDF y los márgenes alrededor de las imágenes. Para obtener más tutoriales, consulte nuestra documentación en línea. Si tiene alguna pregunta, no dude en contactarnos por correo electrónico o en el foro.
Python을 사용하여 이미지를 PDF로 변환
목차
핍으로 설치
pip install Spire.PDF
관련된 링크들
이미지를 PDF로 변환하는 것은 시각적 파일을 휴대 가능하고 보편적으로 읽을 수 있는 형식으로 변환하는 편리하고 효율적인 방법입니다. 스캔한 문서, 사진 또는 디지털 이미지로 작업하는 경우 PDF로 변환하면 다양한 이점을 얻을 수 있습니다. 이미지의 원본 품질을 유지하고 다양한 장치 및 운영 체제에서의 호환성을 보장합니다. 또한 이미지를 PDF로 변환하면 공유, 인쇄, 보관이 쉬워 다양한 전문적, 교육적, 개인적 목적을 위한 다용도 솔루션이 됩니다. 이 문서에서는 다음 방법을 보여주는 몇 가지 예를 제공합니다 Python을 사용하여 이미지를 PDF로 변환합니다.
- Python에서 이미지를 PDF 문서로 변환
- Python에서 여러 이미지를 PDF 문서로 변환
- Python에서 페이지 여백 사용자 정의하기 여러 이미지에서 PDF 만들기
- Python에서 페이지당 여러 이미지가 포함된 PDF 만들기
Python용 PDF 변환기 API
Python 애플리케이션에서 이미지 파일을 PDF 형식으로 변환하려는 경우 Spire.PDF for Python가 도움이 될 수 있습니다. 사용자 정의 페이지 설정(크기 및 여백)을 사용하여 PDF 문서를 만들고, 모든 단일 페이지에 하나 이상의 이미지를 추가하고, 최종 문서를 PDF 파일로 저장할 수 있습니다. PNG, JPEG, BMP, GIF 이미지를 포함한 다양한 이미지 형식이 지원됩니다.
이미지를 PDF로 변환하는 것 외에도 이 라이브러리는 높은 품질과 정밀도로 PDF를 Word로, PDF를 Excel로, PDF를 HTML로, PDF를 PDF/A로 변환하는 것을 지원합니다. 고급 Python PDF 라이브러리인 이 라이브러리는 개발자가 다양한 변환 요구 사항을 충족하도록 변환 옵션을 사용자 정의할 수 있는 풍부한 API도 제공합니다.
다음 pip 명령을 실행하여 설치할 수 있습니다.
pip install Spire.PDF
Python에서 이미지를 PDF로 변환하는 단계
- PdfDocument 클래스를 초기화합니다.
- FromFile 메서드를 사용하여 경로에서 이미지 파일을 로드합니다.
- 문서에 지정된 크기의 페이지를 추가합니다.
- DrawImage 메서드를 사용하여 페이지의 지정된 위치에 이미지를 그립니다.
- SaveToFile 메서드를 사용하여 문서를 PDF 파일로 저장합니다.
Python에서 이미지를 PDF 문서로 변환
이 코드 예제는 빈 문서를 만들고, 이미지와 동일한 크기의 페이지를 추가하고, 페이지에 이미지를 그리는 방식으로 Spire.PDF for Python 라이브러리를 사용하여 이미지 파일을 PDF 문서로 변환합니다.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
doc = PdfDocument()
# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)
# Load a particular image
image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\Images\\img-1.jpg")
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Add a page that has the same size as the image
page = doc.Pages.Add(SizeF(width, height))
# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile("output/ImageToPdf.pdf")
doc.Dispose()

Python에서 여러 이미지를 PDF 문서로 변환
이 예에서는 Spire.PDF for Python를 사용하여 이미지 모음을 PDF 문서로 변환하는 방법을 보여줍니다. 다음 코드 조각은 지정된 폴더에서 이미지를 읽고, PDF 문서를 만들고, 각 이미지를 PDF의 별도 페이지에 추가하고, 결과 PDF 파일을 저장합니다.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for file in files:
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, file))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Add a page that has the same size as the image
page = doc.Pages.Add(SizeF(width, height))
# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile('output/ImagesToPdf.pdf')
doc.Dispose()

Python에서 페이지 여백 사용자 정의하기 여러 이미지에서 PDF 만들기
이 코드 예제는 PDF 문서를 생성하고 이를 지정된 폴더의 이미지로 채우고 페이지 여백을 조정한 후 결과 문서를 파일에 저장합니다.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the left, top, right, bottom page margin
doc.PageSettings.SetMargins(30.0, 30.0, 30.0, 30.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for file in files:
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, file))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Specify page size
size = SizeF(width + doc.PageSettings.Margins.Left + doc.PageSettings.Margins.Right, height + doc.PageSettings.Margins.Top+ doc.PageSettings.Margins.Bottom)
# Add a page with the specified size
page = doc.Pages.Add(size)
# Draw image on the page at (0, 0)
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile('output/CustomizeMargins.pdf')
doc.Dispose()

Python에서 페이지당 여러 이미지가 포함된 PDF 만들기
이 코드는 Python에서 Spire.PDF 라이브러리를 사용하여 페이지당 두 개의 이미지가 포함된 PDF 문서를 만드는 방법을 보여줍니다. 이 예의 이미지는 크기가 동일합니다. 이미지 크기가 일정하지 않은 경우 원하는 결과를 얻으려면 코드를 조정해야 합니다.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the left, top, right, bottom page margins
doc.PageSettings.SetMargins(15.0, 15.0, 15.0, 15.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for i in range(len(files)):
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, files[i]))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Specify page size
size = SizeF(width + doc.PageSettings.Margins.Left + doc.PageSettings.Margins.Right, height*2 + doc.PageSettings.Margins.Top+ doc.PageSettings.Margins.Bottom + 15.0)
if i % 2 == 0:
# Add a page with the specified size
page = doc.Pages.Add(size)
# Draw first image on the page at (0, 0)
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
else :
# Draw second image on the page at (0, height + 15)
page.Canvas.DrawImage(image, 0.0, height + 15.0, width, height)
# Save to file
doc.SaveToFile('output/SeveralImagesPerPage.pdf')
doc.Dispose()

결론
이 블로그 게시물에서는 Spire.PDF for python를 사용하여 페이지당 하나 이상의 이미지가 포함된 이미지에서 PDF 문서를 만드는 방법을 살펴보았습니다. 또한 PDF 페이지 크기와 이미지 주변 여백을 사용자 정의하는 방법을 시연했습니다. 더 많은 튜토리얼을 보려면 다음을 확인하세요 온라인 문서. 질문이 있으시면 언제든지 문의해 주세요 이메일 아니면 법정.
Converti immagine in PDF con Python
Sommario
Installa con Pip
pip install Spire.PDF
Link correlati
La conversione di un'immagine in PDF è un modo comodo ed efficiente per trasformare un file visivo in un formato portatile e universalmente leggibile. Che tu stia lavorando con un documento scansionato, una foto o un'immagine digitale, convertirlo in PDF offre numerosi vantaggi. Mantiene la qualità originale dell'immagine e garantisce la compatibilità tra diversi dispositivi e sistemi operativi. Inoltre, la conversione delle immagini in PDF consente una facile condivisione, stampa e archiviazione, rendendola una soluzione versatile per vari scopi professionali, educativi e personali. Questo articolo fornisce diversi esempi che mostrano come convertire immagini in PDF utilizzando Python.
- Converti un'immagine in un documento PDF in Python
- Converti più immagini in un documento PDF in Python
- Crea un PDF da più immagini personalizzando i margini della pagina in Python
- Crea un PDF con diverse immagini per pagina in Python
API di conversione PDF per Python
Se desideri trasformare i file di immagine in formato PDF in un'applicazione Python, Spire.PDF for Python può aiutarti in questo. Ti consente di creare un documento PDF con impostazioni di pagina personalizzate (dimensioni e margini), aggiungere una o più immagini a ogni singola pagina e salvare il documento finale come file PDF. Sono supportati vari formati di immagine che includono immagini PNG, JPEG, BMP e GIF.
Oltre alla conversione da immagini a PDF, questa libreria supporta la conversione da PDF a Word, da PDF a Excel, da PDF a HTML, da PDF a PDF/Acon alta qualità e precisione. Essendo una libreria PDF Python avanzata, fornisce anche una ricca API che consente agli sviluppatori di personalizzare le opzioni di conversione per soddisfare una varietà di requisiti di conversione.
Puoi installarlo eseguendo il seguente comando pip.
pip install Spire.PDF
Passaggi per convertire un'immagine in PDF in Python
- Inizializza la classe PdfDocument.
- Carica un file immagine dal percorso utilizzando il metodo FromFile.
- Aggiungi una pagina con la dimensione specificata al documento.
- Disegna l'immagine sulla pagina nella posizione specificata utilizzando il metodo DrawImage.
- Salva il documento in un file PDF utilizzando il metodo SaveToFile.
Converti un'immagine in un documento PDF in Python
Questo esempio di codice converte un file immagine in un documento PDF utilizzando la libreria Spire.PDF for Python creando un documento vuoto, aggiungendo una pagina con le stesse dimensioni dell'immagine e disegnando l'immagine sulla pagina.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
doc = PdfDocument()
# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)
# Load a particular image
image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\Images\\img-1.jpg")
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Add a page that has the same size as the image
page = doc.Pages.Add(SizeF(width, height))
# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile("output/ImageToPdf.pdf")
doc.Dispose()

Converti più immagini in un documento PDF in Python
Questo esempio illustra come convertire una raccolta di immagini in un documento PDF utilizzando Spire.PDF for Python. Il seguente frammento di codice legge le immagini da una cartella specificata, crea un documento PDF, aggiunge ciascuna immagine a una pagina separata nel PDF e salva il file PDF risultante.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for file in files:
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, file))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Add a page that has the same size as the image
page = doc.Pages.Add(SizeF(width, height))
# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile('output/ImagesToPdf.pdf')
doc.Dispose()

Crea un PDF da più immagini personalizzando i margini della pagina in Python
Questo esempio di codice crea un documento PDF e lo popola con immagini da una cartella specificata, regola i margini della pagina e salva il documento risultante in un file.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the left, top, right, bottom page margin
doc.PageSettings.SetMargins(30.0, 30.0, 30.0, 30.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for file in files:
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, file))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Specify page size
size = SizeF(width + doc.PageSettings.Margins.Left + doc.PageSettings.Margins.Right, height + doc.PageSettings.Margins.Top+ doc.PageSettings.Margins.Bottom)
# Add a page with the specified size
page = doc.Pages.Add(size)
# Draw image on the page at (0, 0)
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile('output/CustomizeMargins.pdf')
doc.Dispose()

Crea un PDF con diverse immagini per pagina in Python
Questo codice dimostra come utilizzare la libreria Spire.PDF in Python per creare un documento PDF con due immagini per pagina. Le immagini in questo esempio hanno le stesse dimensioni, se la dimensione dell'immagine non è coerente, è necessario modificare il codice per ottenere il risultato desiderato.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the left, top, right, bottom page margins
doc.PageSettings.SetMargins(15.0, 15.0, 15.0, 15.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for i in range(len(files)):
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, files[i]))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Specify page size
size = SizeF(width + doc.PageSettings.Margins.Left + doc.PageSettings.Margins.Right, height*2 + doc.PageSettings.Margins.Top+ doc.PageSettings.Margins.Bottom + 15.0)
if i % 2 == 0:
# Add a page with the specified size
page = doc.Pages.Add(size)
# Draw first image on the page at (0, 0)
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
else :
# Draw second image on the page at (0, height + 15)
page.Canvas.DrawImage(image, 0.0, height + 15.0, width, height)
# Save to file
doc.SaveToFile('output/SeveralImagesPerPage.pdf')
doc.Dispose()

Conclusione
In questo post del blog, abbiamo esplorato come utilizzare Spire.PDF for Python per creare documenti PDF da immagini, contenenti una o più immagini per pagina. Inoltre, abbiamo dimostrato come personalizzare le dimensioni della pagina PDF e i margini attorno alle immagini. Per ulteriori tutorial, consulta la nostra documentazione online. Se avete domande, non esitate a contattarci tramite e-mail o sul Forum.
Convertir une image en PDF avec Python
Table des matières
- API de conversion PDF pour Python
- Étapes pour convertir une image en PDF
- Convertir une image en document PDF
- Convertir plusieurs images en un document PDF
- Créer un PDF à partir de plusieurs images en personnalisant les marges de page
- Créer un PDF avec plusieurs images par page
- Conclusion
- Voir également
Installer avec Pip
pip install Spire.PDF
Liens connexes
La conversion d'une image en PDF est un moyen pratique et efficace de transformer un fichier visuel en un format portable et universellement lisible. Que vous travailliez avec un document numérisé, une photo ou une image numérique, sa conversion en PDF offre de nombreux avantages. Il conserve la qualité originale de l'image et garantit la compatibilité entre divers appareils et systèmes d'exploitation. De plus, la conversion d'images au format PDF permet un partage, une impression et un archivage faciles, ce qui en fait une solution polyvalente à diverses fins professionnelles, éducatives et personnelles. Cet article fournit plusieurs exemples vous montrant comment convertir des images en PDF en utilisant Python.
- Convertir une image en document PDF en Python
- Convertir plusieurs images en un document PDF en python
- Créer un PDF à partir de plusieurs images en personnalisant les marges de page en Python
- Créer un PDF avec plusieurs images par page en Python
API de conversion PDF pour Python
Si vous souhaitez transformer des fichiers image au format PDF dans une application Python, Spire.PDF for Python peut vous aider. Il vous permet de créer un document PDF avec des paramètres de page personnalisés (taille et marges), d'ajouter une ou plusieurs images à chaque page et d'enregistrer le document final sous forme de fichier PDF. Diverses formes d'images sont prises en charge, notamment les images PNG, JPEG, BMP et GIF.
En plus de la conversion d'images en PDF, cette bibliothèque prend en charge la conversion de PDF en Word, PDF en Excel, PDF en HTML, PDF en PDF/A avec une qualité et une précision élevées. En tant que bibliothèque Python PDF avancée, elle fournit également une API riche permettant aux développeurs de personnaliser les options de conversion afin de répondre à diverses exigences de conversion.
Vous pouvez l'installer en exécutant la commande pip suivante.
pip install Spire.PDF
Étapes pour convertir une image en PDF en Python
- Initialisez la classe PdfDocument.
- Chargez un fichier image à partir du chemin à l’aide de la méthode FromFile.
- Ajoutez une page avec la taille spécifiée au document.
- Dessinez l'image sur la page à l'emplacement spécifié à l'aide de la méthode DrawImage.
- Enregistrez le document dans un fichier PDF à l'aide de la méthode SaveToFile.
Convertir une image en document PDF en Python
Cet exemple de code convertit un fichier image en document PDF à l'aide de la bibliothèque Spire.PDF for Python en créant un document vierge, en ajoutant une page avec les mêmes dimensions que l'image et en dessinant l'image sur la page.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument object
doc = PdfDocument()
# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)
# Load a particular image
image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\Images\\img-1.jpg")
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Add a page that has the same size as the image
page = doc.Pages.Add(SizeF(width, height))
# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile("output/ImageToPdf.pdf")
doc.Dispose()

Convertir plusieurs images en un document PDF en python
Cet exemple illustre comment convertir une collection d'images en un document PDF à l'aide de Spire.PDF for Python. L'extrait de code suivant lit les images d'un dossier spécifié, crée un document PDF, ajoute chaque image à une page distincte du PDF et enregistre le fichier PDF résultant.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the page margins to 0
doc.PageSettings.SetMargins(0.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for file in files:
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, file))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Add a page that has the same size as the image
page = doc.Pages.Add(SizeF(width, height))
# Draw image at (0, 0) of the page
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile('output/ImagesToPdf.pdf')
doc.Dispose()

Créer un PDF à partir de plusieurs images en personnalisant les marges de page en Python
Cet exemple de code crée un document PDF et le remplit avec des images d'un dossier spécifié, ajuste les marges de la page et enregistre le document résultant dans un fichier.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the left, top, right, bottom page margin
doc.PageSettings.SetMargins(30.0, 30.0, 30.0, 30.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for file in files:
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, file))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Specify page size
size = SizeF(width + doc.PageSettings.Margins.Left + doc.PageSettings.Margins.Right, height + doc.PageSettings.Margins.Top+ doc.PageSettings.Margins.Bottom)
# Add a page with the specified size
page = doc.Pages.Add(size)
# Draw image on the page at (0, 0)
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
# Save to file
doc.SaveToFile('output/CustomizeMargins.pdf')
doc.Dispose()

Créer un PDF avec plusieurs images par page en Python
Ce code montre comment utiliser la bibliothèque Spire.PDF en Python pour créer un document PDF avec deux images par page. Les images de cet exemple ont la même taille, si la taille de votre image n'est pas cohérente, vous devez alors ajuster le code pour obtenir le résultat souhaité.
- Python
from spire.pdf.common import *
from spire.pdf import *
import os
# Create a PdfDocument object
doc = PdfDocument()
# Set the left, top, right, bottom page margins
doc.PageSettings.SetMargins(15.0, 15.0, 15.0, 15.0)
# Get the folder where the images are stored
path = "C:\\Users\\Administrator\\Desktop\\Images\\"
files = os.listdir(path)
# Iterate through the files in the folder
for root, dirs, files in os.walk(path):
for i in range(len(files)):
# Load a particular image
image = PdfImage.FromFile(os.path.join(root, files[i]))
# Get the image width and height
width = image.PhysicalDimension.Width
height = image.PhysicalDimension.Height
# Specify page size
size = SizeF(width + doc.PageSettings.Margins.Left + doc.PageSettings.Margins.Right, height*2 + doc.PageSettings.Margins.Top+ doc.PageSettings.Margins.Bottom + 15.0)
if i % 2 == 0:
# Add a page with the specified size
page = doc.Pages.Add(size)
# Draw first image on the page at (0, 0)
page.Canvas.DrawImage(image, 0.0, 0.0, width, height)
else :
# Draw second image on the page at (0, height + 15)
page.Canvas.DrawImage(image, 0.0, height + 15.0, width, height)
# Save to file
doc.SaveToFile('output/SeveralImagesPerPage.pdf')
doc.Dispose()

Conclusion
Dans cet article de blog, nous avons expliqué comment utiliser Spire.PDF for python pour créer des documents PDF à partir d'images, contenant une ou plusieurs images par page. De plus, nous avons montré comment personnaliser la taille de la page PDF et les marges autour des images. Pour plus de tutoriels, veuillez consulter notre documentation en ligne. Si vous avez des questions, n'hésitez pas à nous contacter par email ou sur le forum.
Conversão de PDF em texto em Python: recuperar texto de PDFs
Índice
Instalar com Pip
pip install Spire.PDF
Links Relacionados
Na era digital de hoje, a capacidade de extrair informações de documentos PDF de forma rápida e eficiente é crucial para vários setores e profissionais. Quer você seja um pesquisador, um analista de dados ou simplesmente lide com um grande volume de arquivos PDF, ser capaz de converter PDFs em formato de texto editável pode economizar tempo e esforço valiosos. É aqui que Python, uma linguagem de programação versátil e poderosa, vem ao resgate com seus extensos recursos para converter PDF em texto em Python.

Neste artigo, exploraremos como usar Python para PDF para texto conversão, liberando o poder do Python no processamento de arquivos PDF. Este artigo inclui os seguintes tópicos:
- API Python para conversão de PDF em texto
- Guia para converter PDF em texto em Python
- Python para converter PDF em texto sem manter o layout
- Python para converter PDF em texto e manter o layout
- Python para converter uma área específica da página PDF em texto
- Obtenha uma licença gratuita para a API para converter PDF em texto em Python
- Saiba mais sobre processamento de PDF com Python
API Python para conversão de PDF em texto
Para usar Python para conversão de PDF em texto, é necessária uma API de processamento de PDF – Spire.PDF for Python Esta biblioteca Python foi projetada para manipulação de documentos PDF em programas Python, o que capacita os programas Python com várias habilidades de processamento de PDF.
Pudermos baixar Spire.PDF for Python e adicione-o ao nosso projeto, ou simplesmente instale-o através do PyPI com o seguinte código:
pip install Spire.PDF
Guia para converter PDF em texto em Python
Antes de prosseguirmos com a conversão de PDF em texto usando Python, vamos dar uma olhada nas principais vantagens que ele pode nos oferecer:
- Editabilidade: A conversão de PDF em texto permite editar o documento com mais facilidade, pois os arquivos de texto podem ser abertos e editados na maioria dos dispositivos.
- Acessibilidade: Arquivos de texto geralmente são mais acessíveis que PDFs. Quer seja um desktop ou um telefone celular, os arquivos de texto podem ser visualizados em dispositivos com facilidade.
- Integração com outros aplicativos: Os arquivos de texto podem ser integrados perfeitamente em vários aplicativos e fluxos de trabalho.
Etapas para converter documentos PDF em arquivos de texto em Python:
- Instale Spire.PDF for Python.
- Importe módulos.
- Crie um objeto da classe PdfDocument e carregue um arquivo PDF usando o método LoadFromFile().
- Crie um objeto da classe PdfTextExtractOptions e defina as opções de extração de texto, incluindo extrair todo o texto, mostrar texto oculto, extrair apenas texto em uma área especificada e extração simples.
- Obtenha uma página no documento usando o método PdfDocument.Pages.get_Item() e crie objetos PdfTextExtractor com base em cada página para extrair o texto da página usando o método Extract() com opções especificadas.
- Salve o texto extraído como um arquivo de texto e feche o objeto PdfDocument.
Python para converter PDF em texto sem manter layout
Ao usar o método de extração simples para extrair texto de PDF, o programa não reterá as áreas em branco e acompanhará a posição Y atual de cada string e inserirá uma quebra de linha na saída se a posição Y tiver mudado.
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create a string object to store the text
extracted_text = ""
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Set to use simple extraction method
extract_options.IsSimpleExtraction = True
# Loop through the pages in the document
for i in range(pdf.Pages.Count):
# Get a page
page = pdf.Pages.get_Item(i)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
text = text_extractor.ExtractText(extract_options)
# Add the extracted text to the string object
extracted_text += text
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Python para converter PDF em texto e manter o layout
Ao usar o método de extração padrão para extrair texto de PDF, o programa extrairá o texto linha por linha, incluindo espaços em branco.
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create a string object to store the text
extracted_text = ""
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Loop through the pages in the document
for i in range(pdf.Pages.Count):
# Get a page
page = pdf.Pages.get_Item(i)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
text = text_extractor.ExtractText(extract_options)
# Add the extracted text to the string object
extracted_text += text
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Python para converter uma área específica da página PDF em texto
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
from spire.pdf import RectangleF
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Set to extract specific page area
extract_options.ExtractArea = RectangleF(50.0, 220.0, 700.0, 230.0)
# Get a page
page = pdf.Pages.get_Item(0)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
extracted_text = text_extractor.ExtractText(extract_options)
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Obtenha uma licença gratuita para a API para converter PDF em texto em Python
Os usuários podem solicite uma licença temporária gratuita para experimentar o Spire.PDF for Python e avaliar os recursos de conversão de PDF em texto do Python sem quaisquer limitações.
Saiba mais sobre processamento de PDF com Python
Além de converter PDF em texto com Python, também podemos explorar mais recursos de processamento de PDF desta API através das seguintes fontes:
- Como extrair texto de documentos PDF com Python
- Tutoriais para processamento de PDF com Python
- Convertendo documentos PDF baseados em imagem em texto (OCR)
Conclusão
Nesta postagem do blog, exploramos Python em PDF para conversão de texto. Seguindo as etapas operacionais e consultando os exemplos de código do artigo, podemos obter resultados rápidos Conversão de PDF para texto em Python programas. Além disso, o artigo fornece informações sobre os benefícios da conversão de documentos PDF em arquivos de texto. Mais importante ainda, podemos obter mais conhecimento sobre como lidar com documentos PDF com Python e métodos para converter documentos PDF baseados em imagens em texto por meio de ferramentas de OCR a partir das referências do artigo. Se surgir algum problema durante o uso do Spire.PDF for Python, o suporte técnico pode ser obtido entrando em contato com nossa equipe por meio do fórum Spire.PDF ou pore-mail.
Преобразование PDF в текст Python: извлечение текста из PDF-файлов
Оглавление
Установить с помощью Пипа
pip install Spire.PDF
Ссылки по теме
В современную цифровую эпоху возможность быстро и эффективно извлекать информацию из PDF-документов имеет решающее значение для различных отраслей и специалистов. Независимо от того, являетесь ли вы исследователем, аналитиком данных или просто имеете дело с большим объемом PDF-файлов, возможность конвертировать PDF-файлы в редактируемый текстовый формат может сэкономить вам драгоценное время и усилия. Именно здесь на помощь приходит Python, универсальный и мощный язык программирования с его обширными возможностями преобразования PDF в текст на Python.

В этой статье мы рассмотрим, как использовать Python для преобразования PDF в текст преобразование, раскрывающее возможности Python при обработке PDF-файлов. Эта статья включает в себя следующие темы:
- API Python для преобразования PDF в текст
- Руководство по преобразованию PDF в текст в Python
- Python для преобразования PDF в текст без сохранения макета
- Python для преобразования PDF в текст и сохранения макета
- Python для преобразования указанной области страницы PDF в текст
- Получите бесплатную лицензию на API для преобразования PDF в текст на Python
- Узнайте больше об обработке PDF с помощью Python
API Python для преобразования PDF в текст
Чтобы использовать Python для преобразования PDF в текст, необходим API обработки PDF — Spire.PDF for Python Эта библиотека Python предназначена для манипулирования PDF-документами в программах Python, что расширяет возможности программ Python различными возможностями обработки PDF-файлов.
Мы можем скачать Spire.PDF for Python и добавьте его в наш проект или просто установите через PyPI с помощью следующего кода:
pip install Spire.PDF
Руководство по преобразованию PDF в текст в Python
Прежде чем мы приступим к преобразованию PDF в текст с помощью Python, давайте посмотрим на основные преимущества, которые он может нам предложить:
- Возможность редактирования: Преобразование PDF в текст упрощает редактирование документа, поскольку текстовые файлы можно открывать и редактировать на большинстве устройств.
- Доступность: Текстовые файлы обычно более доступны, чем PDF-файлы. Будь то настольный компьютер или мобильный телефон, текстовые файлы можно легко просматривать на устройствах.
- Интеграция с другими приложениями: Текстовые файлы можно легко интегрировать в различные приложения и рабочие процессы.
Шаги по преобразованию PDF-документов в текстовые файлы на Python:
- Установите Spire.PDF for Python.
- Импортируйте модули.
- Создайте объект класса PdfDocument и загрузите PDF-файл с помощью метода LoadFromFile().
- Создайте объект класса PdfTextExtractOptions и установите параметры извлечения текста, включая извлечение всего текста, отображение скрытого текста, извлечение текста только в указанной области и простое извлечение.
- Получите страницу в документе с помощью метода PdfDocument.Pages.get_Item() и создайте объекты PdfTextExtractor на основе каждой страницы для извлечения текста со страницы с помощью метода Extract() с указанными параметрами.
- Сохраните извлеченный текст как текстовый файл и закройте объект PdfDocument.
Python для преобразования PDF в текст без сохранения макета
При использовании простого метода извлечения для извлечения текста из PDF программа не сохраняет пустые области, отслеживает текущую позицию Y каждой строки и вставляет разрыв строки в выходные данные, если позиция Y изменилась.
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create a string object to store the text
extracted_text = ""
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Set to use simple extraction method
extract_options.IsSimpleExtraction = True
# Loop through the pages in the document
for i in range(pdf.Pages.Count):
# Get a page
page = pdf.Pages.get_Item(i)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
text = text_extractor.ExtractText(extract_options)
# Add the extracted text to the string object
extracted_text += text
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Python для преобразования PDF в текст и сохранения макета
При использовании метода извлечения по умолчанию для извлечения текста из PDF программа будет извлекать текст построчно, включая пробелы.
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create a string object to store the text
extracted_text = ""
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Loop through the pages in the document
for i in range(pdf.Pages.Count):
# Get a page
page = pdf.Pages.get_Item(i)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
text = text_extractor.ExtractText(extract_options)
# Add the extracted text to the string object
extracted_text += text
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Python для преобразования указанной области страницы PDF в текст
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
from spire.pdf import RectangleF
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Set to extract specific page area
extract_options.ExtractArea = RectangleF(50.0, 220.0, 700.0, 230.0)
# Get a page
page = pdf.Pages.get_Item(0)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
extracted_text = text_extractor.ExtractText(extract_options)
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Получите бесплатную лицензию на API для преобразования PDF в текст на Python
Пользователи могут подать заявку на получение бесплатной временной лицензии попробовать Spire.PDF for Python и оценить возможности Python PDF в текст без каких-либо ограничений.
Узнайте больше об обработке PDF с помощью Python
Помимо преобразования PDF в текст с помощью Python, мы также можем изучить дополнительные функции обработки PDF с помощью этого API из следующих источников:
- Как извлечь текст из PDF-документов с помощью Python
- Учебники по обработке PDF с помощью Python
- Преобразование PDF-документов на основе изображений в текст (OCR)
Заключение
В этом сообщении блога мы изучили Python в преобразовании PDF в текст. Следуя инструкциям и обращаясь к примерам кода в статье, мы можем добиться быстрого Преобразование PDF в текст в Python программы. Кроме того, в статье представлены преимущества преобразования PDF-документов в текстовые файлы. Что еще более важно, мы можем получить дополнительные знания об обработке PDF-документов с помощью Python и методах преобразования PDF-документов на основе изображений в текст с помощью инструментов OCR из ссылок в статье. Если при использовании Spire.PDF for Python возникнут какие-либо проблемы, техническую поддержку можно получить, обратившись к нашей команде через Форум Spire.PDF или электронная почта.
Python-PDF-zu-Text-Konvertierung: Text aus PDFs abrufen
Inhaltsverzeichnis
Mit Pip installieren
pip install Spire.PDF
verwandte Links
Im heutigen digitalen Zeitalter ist die Fähigkeit, Informationen aus PDF-Dokumenten schnell und effizient zu extrahieren, für verschiedene Branchen und Fachleute von entscheidender Bedeutung. Unabhängig davon, ob Sie ein Forscher oder Datenanalyst sind oder einfach mit einer großen Menge an PDF-Dateien arbeiten, können Sie durch die Konvertierung von PDFs in ein bearbeitbares Textformat wertvolle Zeit und Mühe sparen. Hier kommt Python, eine vielseitige und leistungsstarke Programmiersprache, mit ihren umfangreichen Konvertierungsfunktionen zum Einsatz PDF in Text in Python umwandeln.

In diesem Artikel erfahren Sie, wie Sie es verwenden Python für PDF in Text Konvertierung und entfesselt die Leistungsfähigkeit von Python bei der PDF-Dateiverarbeitung. Dieser Artikel umfasst die folgenden Themen:
- Python-API für die Konvertierung von PDF in Text
- Anleitung zum Konvertieren von PDF in Text in Python
- Python zum Konvertieren von PDF in Text, ohne das Layout beizubehalten
- Python zum Konvertieren von PDF in Text und Beibehalten des Layouts
- Python zum Konvertieren eines bestimmten PDF-Seitenbereichs in Text
- Holen Sie sich eine kostenlose Lizenz für die API zum Konvertieren von PDF in Text in Python
- Erfahren Sie mehr über die PDF-Verarbeitung mit Python
Python-API für die Konvertierung von PDF in Text
Um Python für die Konvertierung von PDF in Text zu verwenden, ist eine PDF-Verarbeitungs-API – Spire.PDF for Python – erforderlich. Diese Python-Bibliothek wurde für die Bearbeitung von PDF-Dokumenten in Python-Programmen entwickelt, wodurch Python-Programme mit verschiedenen PDF-Verarbeitungsfähigkeiten ausgestattet werden.
Wir können Laden Sie Spire.PDF for Python herunter und fügen Sie es unserem Projekt hinzu oder installieren Sie es einfach über PyPI mit dem folgenden Code:
pip install Spire.PDF
Anleitung zum Konvertieren von PDF in Text in Python
Bevor wir mit der Konvertierung von PDF in Text mit Python fortfahren, werfen wir einen Blick auf die wichtigsten Vorteile, die es uns bieten kann:
- Bearbeitbarkeit: Durch das Konvertieren von PDF in Text können Sie das Dokument einfacher bearbeiten, da Textdateien auf den meisten Geräten geöffnet und bearbeitet werden können.
- Barrierefreiheit: Textdateien sind im Allgemeinen besser zugänglich als PDFs. Ganz gleich, ob es sich um einen Desktop oder ein Mobiltelefon handelt, Textdateien können problemlos auf Geräten angezeigt werden.
- Integration mit anderen Anwendungen: Textdateien können nahtlos in verschiedene Anwendungen und Arbeitsabläufe integriert werden.
Schritte zum Konvertieren von PDF-Dokumenten in Textdateien in Python:
- Installieren Spire.PDF for Python.
- Module importieren.
- Erstellen Sie ein Objekt der Klasse PdfDocument und laden Sie eine PDF-Datei mit der Methode LoadFromFile().
- Erstellen Sie ein Objekt der PdfTextExtractOptions-Klasse und legen Sie die Textextraktionsoptionen fest, einschließlich der Extraktion des gesamten Textes, der Anzeige ausgeblendeten Textes, der Extraktion nur des Texts in einem bestimmten Bereich und der einfachen Extraktion.
- Rufen Sie mit der Methode PdfDocument.Pages.get_Item() eine Seite im Dokument ab und erstellen Sie PdfTextExtractor-Objekte basierend auf jeder Seite, um den Text mit der Methode Extract() mit angegebenen Optionen aus der Seite zu extrahieren.
- Speichern Sie den extrahierten Text als Textdatei und schließen Sie das PdfDocument-Objekt.
Python zum Konvertieren von PDF in Text ohne Beibehaltung des Layouts
Wenn Sie die einfache Extraktionsmethode zum Extrahieren von Text aus PDF verwenden, behält das Programm die leeren Bereiche nicht bei und verfolgt nicht die aktuelle Y-Position jeder Zeichenfolge und fügt einen Zeilenumbruch in die Ausgabe ein, wenn sich die Y-Position geändert hat.
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create a string object to store the text
extracted_text = ""
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Set to use simple extraction method
extract_options.IsSimpleExtraction = True
# Loop through the pages in the document
for i in range(pdf.Pages.Count):
# Get a page
page = pdf.Pages.get_Item(i)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
text = text_extractor.ExtractText(extract_options)
# Add the extracted text to the string object
extracted_text += text
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Python zum Konvertieren von PDF in Text und Beibehalten des Layouts
Wenn Sie die Standardextraktionsmethode zum Extrahieren von Text aus PDF verwenden, extrahiert das Programm den Text Zeile für Zeile, einschließlich Leerzeichen.
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create a string object to store the text
extracted_text = ""
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Loop through the pages in the document
for i in range(pdf.Pages.Count):
# Get a page
page = pdf.Pages.get_Item(i)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
text = text_extractor.ExtractText(extract_options)
# Add the extracted text to the string object
extracted_text += text
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Python zum Konvertieren eines bestimmten PDF-Seitenbereichs in Text
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
from spire.pdf import RectangleF
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Set to extract specific page area
extract_options.ExtractArea = RectangleF(50.0, 220.0, 700.0, 230.0)
# Get a page
page = pdf.Pages.get_Item(0)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
extracted_text = text_extractor.ExtractText(extract_options)
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Holen Sie sich eine kostenlose Lizenz für die API zum Konvertieren von PDF in Text in Python
Benutzer können Beantragen Sie eine kostenlose temporäre Lizenz um Spire.PDF für Python auszuprobieren und die Python-PDF-zu-Text-Konvertierungsfunktionen ohne Einschränkungen zu testen.
Erfahren Sie mehr über die PDF-Verarbeitung mit Python
Neben der Konvertierung von PDF in Text mit Python können wir über die folgenden Quellen auch weitere PDF-Verarbeitungsfunktionen dieser API erkunden:
- So extrahieren Sie Text aus PDF-Dokumenten mit Python
- Tutorials zur PDF-Verarbeitung mit Python
- Konvertieren bildbasierter PDF-Dokumente in Text (OCR)
Abschluss
In diesem Blogbeitrag haben wir es untersucht Python in PDF-zu-Text-Konvertierung. Indem wir die Betriebsschritte befolgen und auf die Codebeispiele im Artikel verweisen, können wir schnell etwas erreichen PDF-zu-Text-Konvertierung in Python Programme. Darüber hinaus bietet der Artikel Einblicke in die Vorteile der Konvertierung von PDF-Dokumenten in Textdateien. Noch wichtiger ist, dass wir aus den Referenzen im Artikel weitere Kenntnisse über den Umgang mit PDF-Dokumenten mit Python und Methoden zur Konvertierung bildbasierter PDF-Dokumente in Text mithilfe von OCR-Tools gewinnen können. Sollten bei der Nutzung von Spire.PDF for Python Probleme auftreten, können Sie technischen Support erhalten, indem Sie sich über das Spire.PDF-Forum oder per E-Mail an unser Team wenden.
Conversión de PDF a texto de Python: recuperar texto de archivos PDF
Tabla de contenido
Instalar con Pip
pip install Spire.PDF
enlaces relacionados
En la era digital actual, la capacidad de extraer información de documentos PDF de forma rápida y eficiente es crucial para diversas industrias y profesionales. Ya sea que sea investigador, analista de datos o simplemente trabaje con un gran volumen de archivos PDF, poder convertir archivos PDF a formato de texto editable puede ahorrarle tiempo y esfuerzo valiosos. Aquí es donde Python, un lenguaje de programación potente y versátil, viene al rescate con sus amplias funciones para convertir PDF a texto en Python.

En este artículo, exploraremos cómo usar Python para PDF a texto conversión, liberando el poder de Python en el procesamiento de archivos PDF. Este artículo incluye los siguientes temas:
- API de Python para conversión de PDF a texto
- Guía para convertir PDF a texto en Python
- Python para convertir PDF a texto sin mantener el diseño
- Python para convertir PDF a texto y mantener el diseño
- Python para convertir un área de página PDF especificada en texto
- Obtenga una licencia gratuita para la API para convertir PDF a texto en Python
- Obtenga más información sobre el procesamiento de PDF con Python
API de Python para conversión de PDF a texto
Para utilizar Python para la conversión de PDF a texto, se necesita una API de procesamiento de PDF: Spire.PDF for Python. Esta biblioteca de Python está diseñada para la manipulación de documentos PDF en programas Python, lo que permite a los programas Python varias capacidades de procesamiento de PDF.
Podemos descargar Spire.PDF for Python y agregarlo a nuestro proyecto, o simplemente instalarlo a través de PyPI con el siguiente código:
pip install Spire.PDF
Guía para convertir PDF a texto en Python
Antes de continuar con la conversión de PDF a texto usando Python, veamos las principales ventajas que nos puede ofrecer:
- Editabilidad: Convertir PDF a texto le permite editar el documento más fácilmente, ya que los archivos de texto se pueden abrir y editar en la mayoría de los dispositivos.
- Accesibilidad: los archivos de texto son generalmente más accesibles que los PDF. Ya sea una computadora de escritorio o un teléfono móvil, los archivos de texto se pueden ver en los dispositivos con facilidad.
- Integración con otras aplicaciones: los archivos de texto se pueden integrar perfectamente en varias aplicaciones y flujos de trabajo.
Pasos para convertir documentos PDF a archivos de texto en Python:
- Instale Spire.PDF for Python.
- Importar módulos.
- Cree un objeto de la clase PdfDocument y cargue un archivo PDF usando el método LoadFromFile().
- Cree un objeto de la clase PdfTextExtractOptions y configure las opciones de extracción de texto, incluida la extracción de todo el texto, la visualización de texto oculto, la extracción solo de texto en un área específica y la extracción simple.
- Obtenga una página en el documento usando el método PdfDocument.Pages.get_Item() y cree objetos PdfTextExtractor basados en cada página para extraer el texto de la página usando el método Extract() con opciones específicas.
- Guarde el texto extraído como un archivo de texto y cierre el objeto PdfDocument.
Python para convertir PDF a texto sin mantener el diseño
Cuando se utiliza el método de extracción simple para extraer texto de un PDF, el programa no retendrá las áreas en blanco ni realizará un seguimiento de la posición Y actual de cada cadena ni insertará un salto de línea en la salida si la posición Y ha cambiado.
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create a string object to store the text
extracted_text = ""
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Set to use simple extraction method
extract_options.IsSimpleExtraction = True
# Loop through the pages in the document
for i in range(pdf.Pages.Count):
# Get a page
page = pdf.Pages.get_Item(i)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
text = text_extractor.ExtractText(extract_options)
# Add the extracted text to the string object
extracted_text += text
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Python para convertir PDF a texto y mantener el diseño
Cuando se utiliza el método de extracción predeterminado para extraer texto de un PDF, el programa extraerá el texto línea por línea, incluidos los espacios en blanco.
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create a string object to store the text
extracted_text = ""
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Loop through the pages in the document
for i in range(pdf.Pages.Count):
# Get a page
page = pdf.Pages.get_Item(i)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
text = text_extractor.ExtractText(extract_options)
# Add the extracted text to the string object
extracted_text += text
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Python para convertir un área de página PDF especificada en texto
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
from spire.pdf import RectangleF
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Set to extract specific page area
extract_options.ExtractArea = RectangleF(50.0, 220.0, 700.0, 230.0)
# Get a page
page = pdf.Pages.get_Item(0)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
extracted_text = text_extractor.ExtractText(extract_options)
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Obtenga una licencia gratuita para la API para convertir PDF a texto en Python
Los usuarios pueden solicitar una licencia temporal gratuita Pruebe Spire.PDF for Python y evalúe las funciones de conversión de PDF a texto de Python sin ninguna limitación.
Obtenga más información sobre el procesamiento de PDF con Python
Además de convertir PDF a texto con Python, también podemos explorar más funciones de procesamiento de PDF de esta API a través de las siguientes fuentes:
- Cómo extraer texto de documentos PDF con Python
- Tutoriales para el procesamiento de PDF con Python
- Conversión de documentos PDF basados en imágenes a texto (OCR)
Conclusión
En esta publicación de blog, hemos explorado Python en conversión de PDF a texto. Siguiendo los pasos operativos y consultando los ejemplos de código del artículo, podemos lograr resultados rápidos Conversión de PDF a texto en Python programas. Además, el artículo proporciona información sobre los beneficios de convertir documentos PDF en archivos de texto. Más importante aún, podemos obtener más conocimientos sobre el manejo de documentos PDF con Python y métodos para convertir documentos PDF basados en imágenes en texto a través de herramientas OCR a partir de las referencias del artículo. Si surge algún problema durante el uso de Spire.PDF for Python, puede obtener asistencia técnica comunicándose con nuestro equipo a través del foro de Spire.PDF o por correo electrónico.
Python PDF를 텍스트로 변환: PDF에서 텍스트 검색
목차
핍으로 설치
pip install Spire.PDF
관련된 링크들
오늘날의 디지털 시대에 PDF 문서에서 정보를 빠르고 효율적으로 추출하는 능력은 다양한 산업과 전문가에게 매우 중요합니다. 연구자, 데이터 분석가 또는 단순히 대량의 PDF 파일을 처리하는 경우 PDF를 편집 가능한 텍스트 형식으로 변환하면 귀중한 시간과 노력을 절약할 수 있습니다. 다재다능하고 강력한 프로그래밍 언어인 Python이 변환을 위한 광범위한 기능을 통해 구출되는 곳입니다 Python에서 PDF를 텍스트로.

이번 글에서는 사용법을 알아보겠습니다 PDF를 텍스트로 변환하는 Python 변환하여 PDF 파일 처리에 Python의 강력한 기능을 활용합니다. 이 문서에는 다음 주제가 포함되어 있습니다.
- PDF를 텍스트로 변환하기 위한 Python API
- Python에서 PDF를 텍스트로 변환하기 위한 가이드
- 레이아웃을 유지하지 않고 PDF를 텍스트로 변환하는 Python
- PDF를 텍스트로 변환하고 레이아웃을 유지하는 Python
- 지정된 PDF 페이지 영역을 텍스트로 변환하는 Python
- Python에서 PDF를 텍스트로 변환하는 API에 대한 무료 라이센스 받기
- Python을 사용한 PDF 처리에 대해 자세히 알아보기
PDF를 텍스트로 변환하기 위한 Python API
PDF를 텍스트로 변환하기 위해 Python을 사용하려면 PDF 처리 API인 Spire.PDF for Python가 필요합니다. 이 Python 라이브러리는 Python 프로그램에서 PDF 문서 조작을 위해 설계되었으며, Python 프로그램에 다양한 PDF 처리 기능을 제공합니다.
우리는 할 수 있다 Spire.PDF for Python 다운로드 프로젝트에 추가하거나 다음 코드를 사용하여 PyPI를 통해 간단히 설치하세요.
pip install Spire.PDF
Python에서 PDF를 텍스트로 변환하기 위한 가이드
Python을 사용하여 PDF를 텍스트로 변환하기 전에 Python이 제공할 수 있는 주요 이점을 살펴보겠습니다.
- 편집 가능성: PDF를 텍스트로 변환하면 대부분의 장치에서 텍스트 파일을 열고 편집할 수 있으므로 문서를 더 쉽게 편집할 수 있습니다.
- 접근성: 일반적으로 텍스트 파일은 PDF보다 접근성이 더 높습니다. 데스크톱이든 휴대폰이든 텍스트 파일을 장치에서 쉽게 볼 수 있습니다.
- 다른 애플리케이션과 통합: 텍스트 파일은 다양한 애플리케이션 및 작업 흐름에 원활하게 통합될 수 있습니다.
Python에서 PDF 문서를 텍스트 파일로 변환하는 단계:
- Spire.PDF for Python를 설치합니다.
- 모듈을 가져옵니다.
- PdfDocument 클래스의 객체를 생성하고 LoadFromFile() 메서드를 사용하여 PDF 파일을 로드합니다.
- PdfTextExtractOptions 클래스의 객체를 생성하고 모든 텍스트 추출, 숨겨진 텍스트 표시, 지정된 영역의 텍스트만 추출, 단순 추출을 포함한 텍스트 추출 옵션을 설정합니다.
- PdfDocument.Pages.get_Item() 메소드를 사용하여 문서에서 페이지를 가져오고 각 페이지를 기반으로 PdfTextExtractor 객체를 생성하여 지정된 옵션과 함께 Extract() 메소드를 사용하여 페이지에서 텍스트를 추출합니다.
- 추출된 텍스트를 텍스트 파일로 저장하고 PdfDocument 개체를 닫습니다.
레이아웃 유지 없이 PDF를 텍스트로 변환하는 Python
PDF에서 텍스트를 추출하기 위해 단순 추출 방법을 사용할 때 프로그램은 빈 영역을 유지하지 않고 각 문자열의 현재 Y 위치를 추적하며 Y 위치가 변경된 경우 출력에 줄 바꿈을 삽입합니다.
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create a string object to store the text
extracted_text = ""
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Set to use simple extraction method
extract_options.IsSimpleExtraction = True
# Loop through the pages in the document
for i in range(pdf.Pages.Count):
# Get a page
page = pdf.Pages.get_Item(i)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
text = text_extractor.ExtractText(extract_options)
# Add the extracted text to the string object
extracted_text += text
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

PDF를 텍스트로 변환하고 레이아웃을 유지하는 Python
기본 추출 방법을 사용하여 PDF에서 텍스트를 추출하는 경우 프로그램은 공백을 포함하여 한 줄씩 텍스트를 추출합니다.
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create a string object to store the text
extracted_text = ""
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Loop through the pages in the document
for i in range(pdf.Pages.Count):
# Get a page
page = pdf.Pages.get_Item(i)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
text = text_extractor.ExtractText(extract_options)
# Add the extracted text to the string object
extracted_text += text
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

지정된 PDF 페이지 영역을 텍스트로 변환하는 Python
- Python
from spire.pdf import PdfDocument
from spire.pdf import PdfTextExtractOptions
from spire.pdf import PdfTextExtractor
from spire.pdf import RectangleF
# Create an object of PdfDocument class and load a PDF file
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Create an object of PdfExtractor
extract_options = PdfTextExtractOptions()
# Set to extract specific page area
extract_options.ExtractArea = RectangleF(50.0, 220.0, 700.0, 230.0)
# Get a page
page = pdf.Pages.get_Item(0)
# Create an object of PdfTextExtractor passing the page as paramter
text_extractor = PdfTextExtractor(page)
# Extract the text from the page
extracted_text = text_extractor.ExtractText(extract_options)
# Write the extracted text to a text file
with open("output/ExtractedText.txt", "w") as file:
file.write(extracted_text)
pdf.Close()

Python에서 PDF를 텍스트로 변환하는 API에 대한 무료 라이센스 받기
사용자는 다음을 수행할 수 있습니다 무료 임시 라이센스를 신청하세요 Spire.PDF for Python를 사용해 보고 Python PDF를 텍스트로 변환하는 기능을 제한 없이 평가해 보세요.
Python을 사용한 PDF 처리에 대해 자세히 알아보기
Python을 사용하여 PDF를 텍스트로 변환하는 것 외에도 다음 소스를 통해 이 API의 더 많은 PDF 처리 기능을 탐색할 수도 있습니다.
결론
이번 블로그 게시물에서 우리는 PDF의 Python을 텍스트로 변환합니다. 운영 단계를 따르고 기사의 코드 예제를 참조하면 빠르게 달성할 수 있습니다 Python에서 PDF를 텍스트로 변환 프로그램들. 또한 이 기사는 PDF 문서를 텍스트 파일로 변환할 때의 이점에 대한 통찰력을 제공합니다. 더 중요한 것은 기사의 참고 자료에서 Python을 사용하여 PDF 문서를 처리하는 방법과 OCR 도구를 통해 이미지 기반 PDF 문서를 텍스트로 변환하는 방법에 대한 추가 지식을 얻을 수 있다는 것입니다. Spire.PDF for Python를 사용하는 동안 문제가 발생하는 경우 다음을 통해 당사 팀에 문의하여 기술 지원을 받을 수 있습니다 Spire.PDF 포럼 또는 이메일.