Mesclar PDF é a integração de vários arquivos PDF em um único arquivo PDF. Ele permite que os usuários combinem o conteúdo de vários arquivos PDF relacionados em um único arquivo PDF para melhor categorizar, gerenciar e compartilhar arquivos. Por exemplo, antes de compartilhar um documento, documentos semelhantes podem ser mesclados em um arquivo para simplificar o processo de compartilhamento. Esta postagem mostrará como use Python para mesclar arquivos PDF com código simples.

Biblioteca Python para mesclar arquivos PDF

Spire.PDF for Python é uma biblioteca Python poderosa para criar e manipular arquivos PDF. Com ele, você também pode usar Python para mesclar arquivos PDF sem esforço. Antes disso, precisamos instalar Spire.PDF for Python e plum-dispatch v1.7.4, que pode ser facilmente instalado no VS Code usando os seguintes comandos pip.

pip install Spire.PDF

Este artigo cobre mais detalhes da instalação: Como instalar Spire.PDF for Python no código VS

Mesclar arquivos PDF em Python

Este método suporta a fusão direta de vários arquivos PDF em um único arquivo.

Passos

  • Importe os módulos de biblioteca necessários.
  • Crie uma lista contendo os caminhos dos arquivos PDF a serem mesclados.
  • Use o método Document.MergeFiles(inputFiles: List[str]) para mesclar esses PDFs em um único PDF.
  • Chame o método PdfDocumentBase.Save(filename: str, FileFormat.PDF) para salvar o arquivo mesclado em formato PDF no caminho de saída especificado e liberar recursos.

Código de amostra

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
inputFile1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
inputFile2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
inputFile3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [inputFile1, inputFile2, inputFile3]

# Merge the PDF documents
pdf = PdfDocument.MergeFiles(files)

# Save the result document
pdf.Save("C:/Users/Administrator/Desktop/MergePDF.pdf", FileFormat.PDF)
pdf.Close()

Python Merge PDF Files with Simple Code

Mesclar arquivos PDF clonando páginas em Python

Ao contrário do método acima, este método mescla vários arquivos PDF copiando as páginas do documento e inserindo-as em um novo arquivo.

Passos

  • Importe os módulos de biblioteca necessários.
  • Crie uma lista contendo os caminhos dos arquivos PDF a serem mesclados.
  • Percorra cada arquivo da lista e carregue-o como um objeto PdfDocument; em seguida, adicione-os a uma nova lista.
  • Crie um novo objeto PdfDocument como arquivo de destino.
  • Itere pelos objetos PdfDocument na lista e anexe suas páginas ao novo objeto PdfDocument.
  • Por fim, chame o método PdfDocument.SaveToFile() para salvar o novo objeto PdfDocument no caminho de saída especificado.

Código de amostra

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the pages of the loaded PDF documents into the new PDF document
for pdf in pdfs:
    newPdf.AppendPage(pdf)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/ClonePage.pdf")

Python Merge PDF Files with Simple Code

Mesclar páginas selecionadas de arquivos PDF em Python

Este método é semelhante à mesclagem de PDFs clonando páginas, e você pode especificar as páginas desejadas ao mesclar.

Passos

  • Importe os módulos de biblioteca necessários.
  • Crie uma lista contendo os caminhos dos arquivos PDF a serem mesclados.
  • Percorra cada arquivo da lista e carregue-o como um objeto PdfDocument; em seguida, adicione-os a uma nova lista.
  • Crie um novo objeto PdfDocument como arquivo de destino.
  • Insira as páginas selecionadas dos arquivos carregados no novo objeto PdfDocument usando o método PdfDocument.InsertPage(PdfDocument, pageIndex: int) ou o método PdfDocument.InsertPageRange(PdfDocument, startIndex: int, endIndex: int).
  • Por fim, chame o método PdfDocument.SaveToFile() para salvar o novo objeto PdfDocument no caminho de saída especificado.

Código de amostra

  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the selected pages from the loaded PDF documents into the new document
newPdf.InsertPage(pdfs[0], 0)
newPdf.InsertPage(pdfs[1], 1)
newPdf.InsertPageRange(pdfs[2], 0, 1)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/SelectedPages.pdf")

Python Merge PDF Files with Simple Code

Obtenha uma licença gratuita para a biblioteca mesclar PDF em Python

Você pode obter um licença temporária gratuita de 30 dias do Spire.PDF for Python para mesclar arquivos PDF em Python sem limitações de avaliação.

Conclusão

Neste artigo, você aprendeu como mesclar arquivos PDF em Python. Spire.PDF for Python oferece duas maneiras diferentes de mesclar vários arquivos PDF, incluindo mesclar arquivos diretamente e copiar páginas. Além disso, você pode mesclar páginas selecionadas de vários arquivos PDF com base no segundo método. Em uma palavra, esta biblioteca simplifica o processo e permite que os desenvolvedores se concentrem na construção de aplicativos poderosos que envolvem tarefas de manipulação de PDF.

Veja também

Объединение PDF — это объединение нескольких файлов PDF в один файл PDF. Он позволяет пользователям объединять содержимое нескольких связанных PDF-файлов в один PDF-файл, чтобы лучше классифицировать файлы, управлять ими и обмениваться ими. Например, прежде чем поделиться документом, похожие документы можно объединить в один файл, чтобы упростить процесс обмена. Этот пост покажет вам, как используйте Python для объединения PDF-файлов с помощью простого кода.

Библиотека Python для объединения PDF-файлов

Spire.PDF for Python — это мощная библиотека Python для создания PDF-файлов и управления ими. С его помощью вы также можете использовать Python для легкого объединения PDF-файлов. Перед этим нам нужно установить Spire.PDF for Python и Plum-Dispatch v1.7.4, которые можно легко установить в VS Code с помощью следующих команд pip.

pip install Spire.PDF

В этой статье описывается более подробная информация об установке: Как установить Spire.PDF for Python в VS Code.

Объединение PDF-файлов в Python

Этот метод поддерживает непосредственное объединение нескольких файлов PDF в один файл.

Шаги

  • Импортируйте необходимые библиотечные модули.
  • Создайте список, содержащий пути к PDF-файлам, которые необходимо объединить.
  • Используйте метод Document.MergeFiles(inputFiles: List[str]), чтобы объединить эти PDF-файлы в один PDF-файл.
  • Вызовите метод PdfDocumentBase.Save(filename: str, FileFormat.PDF), чтобы сохранить объединенный файл в формате PDF в указанном пути вывода и освободить ресурсы.

Образец кода

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
inputFile1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
inputFile2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
inputFile3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [inputFile1, inputFile2, inputFile3]

# Merge the PDF documents
pdf = PdfDocument.MergeFiles(files)

# Save the result document
pdf.Save("C:/Users/Administrator/Desktop/MergePDF.pdf", FileFormat.PDF)
pdf.Close()

Python Merge PDF Files with Simple Code

Объединение PDF-файлов путем клонирования страниц в Python

В отличие от описанного выше метода, этот метод объединяет несколько файлов PDF путем копирования страниц документа и вставки их в новый файл.

Шаги

  • Импортируйте необходимые библиотечные модули.
  • Создайте список, содержащий пути к PDF-файлам, которые необходимо объединить.
  • Прокрутите каждый файл в списке и загрузите его как объект PdfDocument; затем добавьте их в новый список.
  • Создайте новый объект PdfDocument в качестве целевого файла.
  • Перебирайте объекты PdfDocument в списке и добавляйте их страницы к новому объекту PdfDocument.
  • Наконец, вызовите метод PdfDocument.SaveToFile(), чтобы сохранить новый объект PdfDocument в указанном пути вывода.

Образец кода

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the pages of the loaded PDF documents into the new PDF document
for pdf in pdfs:
    newPdf.AppendPage(pdf)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/ClonePage.pdf")

Python Merge PDF Files with Simple Code

Объединить выбранные страницы PDF-файлов в Python

Этот метод аналогичен объединению PDF-файлов путем клонирования страниц, и при объединении вы можете указать нужные страницы.

Шаги

  • Импортируйте необходимые библиотечные модули.
  • Создайте список, содержащий пути к PDF-файлам, которые необходимо объединить.
  • Прокрутите каждый файл в списке и загрузите его как объект PdfDocument; затем добавьте их в новый список.
  • Создайте новый объект PdfDocument в качестве целевого файла.
  • Вставьте выбранные страницы из загруженных файлов в новый объект PdfDocument с помощью метода PdfDocument.InsertPage(PdfDocument, pageIndex: int) или метода PdfDocument.InsertPageRange(PdfDocument, startIndex: int, endIndex: int).
  • Наконец, вызовите метод PdfDocument.SaveToFile(), чтобы сохранить новый объект PdfDocument в указанном пути вывода.

Образец кода

  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the selected pages from the loaded PDF documents into the new document
newPdf.InsertPage(pdfs[0], 0)
newPdf.InsertPage(pdfs[1], 1)
newPdf.InsertPageRange(pdfs[2], 0, 1)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/SelectedPages.pdf")

Python Merge PDF Files with Simple Code

Получите бесплатную лицензию на библиотеку для объединения PDF-файлов в Python

Вы можете получить бесплатная 30-дневная временная лицензия Spire.PDF for Python для объединения PDF-файлов в Python без ограничений оценки.

Заключение

В этой статье вы узнали, как объединять PDF-файлы в Python. Spire.PDF for Python предоставляет два разных способа объединения нескольких файлов PDF, включая непосредственное объединение файлов и копирование страниц. Кроме того, вы можете объединить выбранные страницы нескольких файлов PDF, используя второй метод. Одним словом, эта библиотека упрощает процесс и позволяет разработчикам сосредоточиться на создании мощных приложений, выполняющих задачи по манипулированию PDF-файлами.

Смотрите также

Beim Zusammenführen von PDF handelt es sich um die Integration mehrerer PDF-Dateien in eine einzige PDF-Datei. Es ermöglicht Benutzern, die Inhalte mehrerer zusammengehöriger PDF-Dateien in einer einzigen PDF-Datei zu kombinieren, um Dateien besser zu kategorisieren, zu verwalten und zu teilen. Beispielsweise können vor der Freigabe eines Dokuments ähnliche Dokumente in einer Datei zusammengeführt werden, um den Freigabevorgang zu vereinfachen. Dieser Beitrag zeigt Ihnen, wie es geht Verwenden Sie Python, um PDF-Dateien mit einfachem Code zusammenzuführen.

Python-Bibliothek zum Zusammenführen von PDF-Dateien

Spire.PDF for Python ist eine leistungsstarke Python-Bibliothek zum Erstellen und Bearbeiten von PDF-Dateien. Damit können Sie mit Python auch PDF-Dateien mühelos zusammenführen. Vorher müssen wir installieren Spire.PDF for Python und plum-dispatch v1.7.4, das mit den folgenden Pip-Befehlen einfach in VS Code installiert werden kann.

pip install Spire.PDF

Dieser Artikel behandelt weitere Details der Installation: So installieren Sie Spire.PDF for Python in VS Code

PDF-Dateien in Python zusammenführen

Diese Methode unterstützt das direkte Zusammenführen mehrerer PDF-Dateien zu einer einzigen Datei.

Schritte

  • Importieren Sie die erforderlichen Bibliotheksmodule.
  • Erstellen Sie eine Liste mit den Pfaden der zusammenzuführenden PDF-Dateien.
  • Verwenden Sie die Methode Document.MergeFiles(inputFiles: List[str]), um diese PDFs zu einer einzigen PDF zusammenzuführen.
  • Rufen Sie die Methode PdfDocumentBase.Save(filename: str, FileFormat.PDF) auf, um die zusammengeführte Datei im PDF-Format im angegebenen Ausgabepfad zu speichern und Ressourcen freizugeben.

Beispielcode

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
inputFile1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
inputFile2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
inputFile3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [inputFile1, inputFile2, inputFile3]

# Merge the PDF documents
pdf = PdfDocument.MergeFiles(files)

# Save the result document
pdf.Save("C:/Users/Administrator/Desktop/MergePDF.pdf", FileFormat.PDF)
pdf.Close()

Python Merge PDF Files with Simple Code

Führen Sie PDF-Dateien durch Klonen von Seiten in Python zusammen

Im Gegensatz zur oben genannten Methode führt diese Methode mehrere PDF-Dateien zusammen, indem Dokumentseiten kopiert und in eine neue Datei eingefügt werden.

Schritte

  • Importieren Sie die erforderlichen Bibliotheksmodule.
  • Erstellen Sie eine Liste mit den Pfaden der zusammenzuführenden PDF-Dateien.
  • Durchlaufen Sie jede Datei in der Liste und laden Sie sie als PdfDocument-Objekt. Fügen Sie sie dann einer neuen Liste hinzu.
  • Erstellen Sie ein neues PdfDocument-Objekt als Zieldatei.
  • Durchlaufen Sie die PdfDocument-Objekte in der Liste und hängen Sie ihre Seiten an das neue PdfDocument-Objekt an.
  • Rufen Sie abschließend die Methode PdfDocument.SaveToFile() auf, um das neue PdfDocument-Objekt im angegebenen Ausgabepfad zu speichern.

Sample Code

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the pages of the loaded PDF documents into the new PDF document
for pdf in pdfs:
    newPdf.AppendPage(pdf)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/ClonePage.pdf")

Python Merge PDF Files with Simple Code

Ausgewählte Seiten von PDF-Dateien in Python zusammenführen

Diese Methode ähnelt dem Zusammenführen von PDFs durch Klonen von Seiten, und Sie können beim Zusammenführen die gewünschten Seiten angeben.

Schritte

  • Importieren Sie die erforderlichen Bibliotheksmodule.
  • Erstellen Sie eine Liste mit den Pfaden der zusammenzuführenden PDF-Dateien.
  • Durchlaufen Sie jede Datei in der Liste und laden Sie sie als PdfDocument-Objekt. Fügen Sie sie dann einer neuen Liste hinzu.
  • Erstellen Sie ein neues PdfDocument-Objekt als Zieldatei.
  • Fügen Sie die ausgewählten Seiten aus den geladenen Dateien mit der Methode PdfDocument.InsertPage(PdfDocument, pageIndex: int) oder der Methode PdfDocument.InsertPageRange(PdfDocument, startIndex: int, endIndex: int) in das neue PdfDocument-Objekt ein.
  • Rufen Sie abschließend die Methode PdfDocument.SaveToFile() auf, um das neue PdfDocument-Objekt im angegebenen Ausgabepfad zu speichern.

Beispielcode

  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the selected pages from the loaded PDF documents into the new document
newPdf.InsertPage(pdfs[0], 0)
newPdf.InsertPage(pdfs[1], 1)
newPdf.InsertPageRange(pdfs[2], 0, 1)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/SelectedPages.pdf")

Python Merge PDF Files with Simple Code

Holen Sie sich eine kostenlose Lizenz für die Bibliothek zum Zusammenführen von PDF-Dateien in Python

Sie können eine bekommen kostenlose 30-tägige temporäre Lizenz von Spire.PDF for Python zum Zusammenführen von PDF-Dateien in Python ohne Auswertungseinschränkungen.

Abschluss

In diesem Artikel haben Sie erfahren, wie Sie PDF-Dateien in Python zusammenführen. Spire.PDF for Python bietet zwei verschiedene Möglichkeiten zum Zusammenführen mehrerer PDF-Dateien, einschließlich des direkten Zusammenführens von Dateien und des Kopierens von Seiten. Mit der zweiten Methode können Sie auch ausgewählte Seiten mehrerer PDF-Dateien zusammenführen. Kurz gesagt, diese Bibliothek vereinfacht den Prozess und ermöglicht es Entwicklern, sich auf die Erstellung leistungsstarker Anwendungen zu konzentrieren, die PDF-Manipulationsaufgaben beinhalten.

Siehe auch

Fusionar PDF es la integración de varios archivos PDF en un solo archivo PDF. Permite a los usuarios combinar el contenido de varios archivos PDF relacionados en un solo archivo PDF para categorizar, administrar y compartir mejor los archivos. Por ejemplo, antes de compartir un documento, se pueden combinar documentos similares en un solo archivo para simplificar el proceso de compartir. Esta publicación le mostrará cómo use Python para fusionar archivos PDF con código simple.

Biblioteca Python para fusionar archivos PDF

Spire.PDF for Python es una poderosa biblioteca de Python para crear y manipular archivos PDF. Con él, también puedes usar Python para fusionar archivos PDF sin esfuerzo. Antes de eso, necesitamos instalar Spire.PDF for Python y plum-dispatch v1.7.4, que se puede instalar fácilmente en VS Code usando los siguientes comandos pip.

pip install Spire.PDF

Este artículo cubre más detalles de la instalación: Cómo instalar Spire.PDF for Python en VS Code

Fusionar archivos PDF en Python

Este método admite la combinación directa de varios archivos PDF en un solo archivo.

Pasos

  • Importe los módulos de biblioteca necesarios.
  • Cree una lista que contenga las rutas de los archivos PDF que se fusionarán.
  • Utilice el método Document.MergeFiles(inputFiles: List[str]) para fusionar estos archivos PDF en un solo PDF.
  • Llame al método PdfDocumentBase.Save(filename: str, FileFormat.PDF) para guardar el archivo combinado en formato PDF en la ruta de salida especificada y liberar recursos.

Código de muestra

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
inputFile1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
inputFile2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
inputFile3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [inputFile1, inputFile2, inputFile3]

# Merge the PDF documents
pdf = PdfDocument.MergeFiles(files)

# Save the result document
pdf.Save("C:/Users/Administrator/Desktop/MergePDF.pdf", FileFormat.PDF)
pdf.Close()

Python Merge PDF Files with Simple Code

Fusionar archivos PDF clonando páginas en Python

A diferencia del método anterior, este método combina varios archivos PDF copiando páginas del documento e insertándolas en un archivo nuevo.

Pasos

  • Importe los módulos de biblioteca necesarios.
  • Cree una lista que contenga las rutas de los archivos PDF que se fusionarán.
  • Recorra cada archivo de la lista y cárguelo como un objeto PdfDocument; luego agréguelos a una nueva lista.
  • Cree un nuevo objeto PdfDocument como archivo de destino.
  • Itere a través de los objetos PdfDocument en la lista y agregue sus páginas al nuevo objeto PdfDocument.
  • Finalmente, llame al método PdfDocument.SaveToFile() para guardar el nuevo objeto PdfDocument en la ruta de salida especificada.

Código de muestra

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the pages of the loaded PDF documents into the new PDF document
for pdf in pdfs:
    newPdf.AppendPage(pdf)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/ClonePage.pdf")

Python Merge PDF Files with Simple Code

Fusionar páginas seleccionadas de archivos PDF en Python

Este método es similar a fusionar archivos PDF mediante la clonación de páginas y puede especificar las páginas deseadas al fusionar.

Pasos

  • Importe los módulos de biblioteca necesarios.
  • Cree una lista que contenga las rutas de los archivos PDF que se fusionarán.
  • Recorra cada archivo de la lista y cárguelo como un objeto PdfDocument; luego agréguelos a una nueva lista.
  • Cree un nuevo objeto PdfDocument como archivo de destino.
  • Inserte las páginas seleccionadas de los archivos cargados en el nuevo objeto PdfDocument utilizando el método PdfDocument.InsertPage(PdfDocument, pageIndex: int) o el método PdfDocument.InsertPageRange(PdfDocument, startIndex: int, endIndex: int).
  • Finalmente, llame al método PdfDocument.SaveToFile() para guardar el nuevo objeto PdfDocument en la ruta de salida especificada.

Código de muestra

  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the selected pages from the loaded PDF documents into the new document
newPdf.InsertPage(pdfs[0], 0)
newPdf.InsertPage(pdfs[1], 1)
newPdf.InsertPageRange(pdfs[2], 0, 1)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/SelectedPages.pdf")

Python Merge PDF Files with Simple Code

Obtenga una licencia gratuita para que la biblioteca combine PDF en Python

Puedes conseguir un licencia temporal gratuita de 30 días de Spire.PDF for Python para fusionar archivos PDF en Python sin limitaciones de evaluación.

Conclusión

En este artículo, has aprendido cómo fusionar archivos PDF en Python. Spire.PDF for Python proporciona dos formas diferentes de fusionar varios archivos PDF, incluida la fusión de archivos directamente y la copia de páginas. Además, puede fusionar páginas seleccionadas de varios archivos PDF según el segundo método. En una palabra, esta biblioteca simplifica el proceso y permite a los desarrolladores centrarse en crear aplicaciones potentes que impliquen tareas de manipulación de PDF.

Ver también

PDF 병합은 여러 PDF 파일을 단일 PDF 파일로 통합하는 것입니다. 이를 통해 사용자는 여러 관련 PDF 파일의 내용을 단일 PDF 파일로 결합하여 파일을 더 효과적으로 분류, 관리 및 공유할 수 있습니다. 예를 들어, 문서를 공유하기 전에 유사한 문서를 하나의 파일로 병합하여 공유 프로세스를 단순화할 수 있습니다. 이 게시물에서는 방법을 보여줍니다 Python을 사용하여 PDF 파일을 간단한 코드로 병합.

PDF 파일 병합을 위한 Python 라이브러리

Spire.PDF for Python는 PDF 파일을 생성하고 조작하기 위한 강력한 Python 라이브러리입니다. 이를 통해 Python을 사용하여 PDF 파일을 쉽게 병합할 수도 있습니다. 그 전에 설치를 해야 합니다 Spire.PDF for PythonPlum-dispatch v1.7.4는 다음 pip 명령을 사용하여 VS Code에 쉽게 설치할 수 있습니다.

pip install Spire.PDF

이 문서에서는 설치에 대한 자세한 내용을 다룹니다. VS Code에서 Spire.PDF for Python를 설치하는 방법

Python에서 PDF 파일 병합

이 방법은 여러 PDF 파일을 단일 파일로 직접 병합하는 것을 지원합니다.

단계

  • 필요한 라이브러리 모듈을 가져옵니다.
  • 병합할 PDF 파일의 경로가 포함된 목록을 만듭니다.
  • Document.MergeFiles(inputFiles: List[str]) 메서드를 사용하여 이러한 PDF를 단일 PDF로 병합합니다.
  • PdfDocumentBase.Save(filename: str, FileFormat.PDF) 메서드를 호출하여 병합된 파일을 PDF 형식으로 지정된 출력 경로 및 릴리스 리소스에 저장합니다.

샘플 코드

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
inputFile1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
inputFile2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
inputFile3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [inputFile1, inputFile2, inputFile3]

# Merge the PDF documents
pdf = PdfDocument.MergeFiles(files)

# Save the result document
pdf.Save("C:/Users/Administrator/Desktop/MergePDF.pdf", FileFormat.PDF)
pdf.Close()

Python Merge PDF Files with Simple Code

Python에서 페이지를 복제하여 PDF 파일 병합

위의 방법과 달리 이 방법은 문서 페이지를 복사하여 새 파일에 삽입하여 여러 PDF 파일을 병합합니다.

단계

  • 필요한 라이브러리 모듈을 가져옵니다.
  • 병합할 PDF 파일의 경로가 포함된 목록을 만듭니다.
  • 목록의 각 파일을 반복하여 PdfDocument 개체로 로드합니다. 그런 다음 새 목록에 추가하십시오.
  • PdfDocument 개체를 대상 파일로 만듭니다.
  • 목록의 PdfDocument 개체를 반복하고 해당 페이지를 새 PdfDocument 개체에 추가합니다.
  • 마지막으로 PdfDocument.SaveToFile() 메서드를 호출하여 새 PdfDocument 개체를 지정된 출력 경로에 저장합니다.

샘플 코드

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the pages of the loaded PDF documents into the new PDF document
for pdf in pdfs:
    newPdf.AppendPage(pdf)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/ClonePage.pdf")

Python Merge PDF Files with Simple Code

Python에서 선택한 PDF 파일 페이지 병합

이 방법은 페이지를 복제하여 PDF를 병합하는 것과 유사하며 병합 시 원하는 페이지를 지정할 수 있습니다.

단계

  • 필요한 라이브러리 모듈을 가져옵니다.
  • 병합할 PDF 파일의 경로가 포함된 목록을 만듭니다.
  • 목록의 각 파일을 반복하여 PdfDocument 개체로 로드합니다. 그런 다음 새 목록에 추가하십시오.
  • PdfDocument 개체를 대상 파일로 만듭니다.
  • PdfDocument.InsertPage(PdfDocument, pageIndex: int) 메서드 또는 PdfDocument.InsertPageRange(PdfDocument, startIndex: int, endIndex: int) 메서드를 사용하여 로드된 파일에서 선택한 페이지를 새 PdfDocument 개체에 삽입합니다.
  • 마지막으로 PdfDocument.SaveToFile() 메서드를 호출하여 새 PdfDocument 개체를 지정된 출력 경로에 저장합니다.

샘플 코드

  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the selected pages from the loaded PDF documents into the new document
newPdf.InsertPage(pdfs[0], 0)
newPdf.InsertPage(pdfs[1], 1)
newPdf.InsertPageRange(pdfs[2], 0, 1)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/SelectedPages.pdf")

Python Merge PDF Files with Simple Code

Python에서 PDF를 병합하려면 라이브러리에 대한 무료 라이센스를 받으세요

당신은 얻을 수 있습니다 무료 30일 임시 라이센스 Spire.PDF for Python를 사용하면 평가 제한 없이 Python에서 PDF 파일을 병합할 수 있습니다.

결론

이 기사에서는 Python에서 PDF 파일을 병합하는 방법을 배웠습니다. Spire.PDF for Python는 파일을 직접 병합하고 페이지를 복사하는 것을 포함하여 여러 PDF 파일을 병합하는 두 가지 방법을 제공합니다. 또한 두 번째 방법을 기반으로 여러 PDF 파일 중 선택한 페이지를 병합할 수 있습니다. 한마디로 이 라이브러리는 프로세스를 단순화하고 개발자가 PDF 조작 작업과 관련된 강력한 응용 프로그램을 구축하는 데 집중할 수 있도록 합니다.

또한보십시오

Tuesday, 09 January 2024 02:33

Python Unisci file PDF con codice semplice

L'unione di PDF è l'integrazione di più file PDF in un unico file PDF. Consente agli utenti di combinare il contenuto di più file PDF correlati in un unico file PDF per classificare, gestire e condividere meglio i file. Ad esempio, prima di condividere un documento, documenti simili possono essere uniti in un unico file per semplificare il processo di condivisione. Questo post ti mostrerà come farlo usa Python per unire file PDF con codice semplice.

Libreria Python per unire file PDF

Spire.PDF for Python è una potente libreria Python per creare e manipolare file PDF. Con esso, puoi anche utilizzare Python per unire file PDF senza sforzo. Prima di ciò, dobbiamo installare Spire.PDF for Python e plum-dispatch v1.7.4, che può essere facilmente installato in VS Code utilizzando i seguenti comandi pip.

pip install Spire.PDF

Questo articolo copre ulteriori dettagli dell'installazione: Come installare Spire.PDF for Python in VS Code

Unisci file PDF in Python

Questo metodo supporta l'unione diretta di più file PDF in un unico file.

Passi

  • Importa i moduli della libreria richiesti.
  • Crea un elenco contenente i percorsi dei file PDF da unire.
  • Utilizza il metodo Document.MergeFiles(inputFiles: List[str]) per unire questi PDF in un unico PDF.
  • Chiama il metodo PdfDocumentBase.Save(filename: str, FileFormat.PDF) per salvare il file unito in formato PDF nel percorso di output specificato e rilasciare le risorse.

Codice d'esempio

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
inputFile1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
inputFile2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
inputFile3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [inputFile1, inputFile2, inputFile3]

# Merge the PDF documents
pdf = PdfDocument.MergeFiles(files)

# Save the result document
pdf.Save("C:/Users/Administrator/Desktop/MergePDF.pdf", FileFormat.PDF)
pdf.Close()

Python Merge PDF Files with Simple Code

Unisci file PDF clonando pagine in Python

A differenza del metodo precedente, questo metodo unisce più file PDF copiando le pagine del documento e inserendole in un nuovo file.

Passi

  • Importa i moduli della libreria richiesti.
  • Crea un elenco contenente i percorsi dei file PDF da unire.
  • Passa in rassegna ogni file nell'elenco e caricalo come oggetto PdfDocument; quindi aggiungerli a un nuovo elenco.
  • Crea un nuovo oggetto PdfDocument come file di destinazione.
  • Scorri gli oggetti PdfDocument nell'elenco e aggiungi le relative pagine al nuovo oggetto PdfDocument.
  • Infine, chiama il metodo PdfDocument.SaveToFile() per salvare il nuovo oggetto PdfDocument nel percorso di output specificato.

Codice d'esempio

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the pages of the loaded PDF documents into the new PDF document
for pdf in pdfs:
    newPdf.AppendPage(pdf)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/ClonePage.pdf")

Python Merge PDF Files with Simple Code

Unisci le pagine selezionate di file PDF in Python

Questo metodo è simile all'unione di PDF clonando le pagine e puoi specificare le pagine desiderate durante l'unione.

Passi

  • Importa i moduli della libreria richiesti.
  • Crea un elenco contenente i percorsi dei file PDF da unire.
  • Passa in rassegna ogni file nell'elenco e caricalo come oggetto PdfDocument; quindi aggiungerli a un nuovo elenco.
  • Crea un nuovo oggetto PdfDocument come file di destinazione.
  • Inserire le pagine selezionate dai file caricati nel nuovo oggetto PdfDocument utilizzando il metodo PdfDocument.InsertPage(PdfDocument, pageIndex: int) o il metodo PdfDocument.InsertPageRange(PdfDocument, startIndex: int, endIndex: int).
  • Infine, chiama il metodo PdfDocument.SaveToFile() per salvare il nuovo oggetto PdfDocument nel percorso di output specificato.

Codice d'esempio

  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the selected pages from the loaded PDF documents into the new document
newPdf.InsertPage(pdfs[0], 0)
newPdf.InsertPage(pdfs[1], 1)
newPdf.InsertPageRange(pdfs[2], 0, 1)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/SelectedPages.pdf")

Python Merge PDF Files with Simple Code

Ottieni una licenza gratuita per la libreria per unire PDF in Python

Puoi ottenere un licenza temporanea gratuita di 30 giorni di Spire.PDF for Python per unire file PDF in Python senza limitazioni di valutazione.

Conclusione

In questo articolo hai imparato come unire file PDF in Python. Spire.PDF for Python fornisce due modi diversi per unire più file PDF, inclusa l'unione diretta dei file e la copia delle pagine. Inoltre, puoi unire pagine selezionate di più file PDF in base al secondo metodo. In una parola, questa libreria semplifica il processo e consente agli sviluppatori di concentrarsi sulla creazione di potenti applicazioni che implicano attività di manipolazione dei PDF.

Guarda anche

La fusion de PDF est l'intégration de plusieurs fichiers PDF en un seul fichier PDF. Il permet aux utilisateurs de combiner le contenu de plusieurs fichiers PDF associés en un seul fichier PDF pour mieux catégoriser, gérer et partager des fichiers. Par exemple, avant de partager un document, des documents similaires peuvent être fusionnés en un seul fichier pour simplifier le processus de partage. Cet article vous montrera comment utilisez Python pour fusionner des fichiers PDF avec un code simple.

Bibliothèque Python pour fusionner des fichiers PDF

Spire.PDF for Python est une puissante bibliothèque Python permettant de créer et de manipuler des fichiers PDF. Avec lui, vous pouvez également utiliser Python pour fusionner des fichiers PDF sans effort. Avant cela, nous devons installer Spire.PDF for Python et plum-dispatch v1.7.4, qui peut être facilement installé dans VS Code à l'aide des commandes pip suivantes.

pip install Spire.PDF

Cet article couvre plus de détails sur l'installation: Comment installer Spire.PDF for Python dans VS Code

Fusionner des fichiers PDF en Python

Cette méthode prend en charge la fusion directe de plusieurs fichiers PDF en un seul fichier.

Pas

  • Importez les modules de bibliothèque requis.
  • Créez une liste contenant les chemins des fichiers PDF à fusionner.
  • Utilisez la méthode Document.MergeFiles(inputFiles: List[str]) pour fusionner ces PDF en un seul PDF.
  • Appelez la méthode PdfDocumentBase.Save(filename: str, FileFormat.PDF) pour enregistrer le fichier fusionné au format PDF dans le chemin de sortie spécifié et libérer les ressources.

Exemple de code

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
inputFile1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
inputFile2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
inputFile3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [inputFile1, inputFile2, inputFile3]

# Merge the PDF documents
pdf = PdfDocument.MergeFiles(files)

# Save the result document
pdf.Save("C:/Users/Administrator/Desktop/MergePDF.pdf", FileFormat.PDF)
pdf.Close()

Python Merge PDF Files with Simple Code

Fusionner des fichiers PDF en clonant des pages en Python

Contrairement à la méthode ci-dessus, cette méthode fusionne plusieurs fichiers PDF en copiant les pages du document et en les insérant dans un nouveau fichier.

Pas

  • Importez les modules de bibliothèque requis.
  • Créez une liste contenant les chemins des fichiers PDF à fusionner.
  • Parcourez chaque fichier de la liste et chargez-le en tant qu'objet PdfDocument ; puis ajoutez-les à une nouvelle liste.
  • Créez un nouvel objet PdfDocument comme fichier de destination.
  • Parcourez les objets PdfDocument dans la liste et ajoutez leurs pages au nouvel objet PdfDocument.
  • Enfin, appelez la méthode PdfDocument.SaveToFile() pour enregistrer le nouvel objet PdfDocument dans le chemin de sortie spécifié.

Exemple de code

  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the pages of the loaded PDF documents into the new PDF document
for pdf in pdfs:
    newPdf.AppendPage(pdf)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/ClonePage.pdf")

Python Merge PDF Files with Simple Code

Fusionner les pages sélectionnées de fichiers PDF en Python

Cette méthode est similaire à la fusion de PDF par clonage de pages, et vous pouvez spécifier les pages souhaitées lors de la fusion.

Pas

  • Importez les modules de bibliothèque requis.
  • Créez une liste contenant les chemins des fichiers PDF à fusionner.
  • Parcourez chaque fichier de la liste et chargez-le en tant qu'objet PdfDocument ; puis ajoutez-les à une nouvelle liste.
  • Créez un nouvel objet PdfDocument comme fichier de destination.
  • Insérez les pages sélectionnées à partir des fichiers chargés dans le nouvel objet PdfDocument à l'aide de la méthode PdfDocument.InsertPage(PdfDocument, pageIndex: int) ou PdfDocument.InsertPageRange(PdfDocument, startIndex: int, endIndex: int).
  • Enfin, appelez la méthode PdfDocument.SaveToFile() pour enregistrer le nouvel objet PdfDocument dans le chemin de sortie spécifié.

Exemple de code

  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a list of the PDF file paths
file1 = "C:/Users/Administrator/Desktop/PDFs/Sample-1.pdf"
file2 = "C:/Users/Administrator/Desktop/PDFs/Sample-2.pdf"
file3 = "C:/Users/Administrator/Desktop/PDFs/Sample-3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the selected pages from the loaded PDF documents into the new document
newPdf.InsertPage(pdfs[0], 0)
newPdf.InsertPage(pdfs[1], 1)
newPdf.InsertPageRange(pdfs[2], 0, 1)

# Save the new PDF document
newPdf.SaveToFile("C:/Users/Administrator/Desktop/SelectedPages.pdf")

Python Merge PDF Files with Simple Code

Obtenez une licence gratuite pour la bibliothèque pour fusionner des PDF en Python

Vous pouvez obtenir un licence temporaire gratuite de 30 jours de Spire.PDF for Python pour fusionner des fichiers PDF en Python sans limitations d'évaluation.

Conclusion

Dans cet article, vous avez appris à fusionner des fichiers PDF en Python. Spire.PDF for Python propose deux manières différentes de fusionner plusieurs fichiers PDF, notamment la fusion directe de fichiers et la copie de pages. En outre, vous pouvez fusionner les pages sélectionnées de plusieurs fichiers PDF en fonction de la deuxième méthode. En un mot, cette bibliothèque simplifie le processus et permet aux développeurs de se concentrer sur la création d'applications puissantes impliquant des tâches de manipulation de PDF.

Voir également

Os modelos fornecem estrutura e layout prontos, economizando tempo e esforço na criação de documentos do zero. Em vez de projetar o layout do documento, os estilos de formatação e a organização das seções, você pode simplesmente escolher um modelo que atenda aos seus requisitos e começar a adicionar seu conteúdo. Isso é particularmente útil quando você precisa criar vários documentos com uma aparência consistente. Neste blog, exploraremos como crie documentos do Word a partir de modelos usando Python.

Discutiremos três abordagens diferentes para gerar documentos Word a partir de modelos:

Biblioteca Python para criar documentos do Word a partir de modelos

Para começar, precisamos instalar o módulo Python necessário que suporta a geração de documentos Word a partir de modelos. Nesta postagem do blog, usaremos a biblioteca Spire.Doc for Python .

Spire.Doc for Python oferece um conjunto abrangente de recursos para criar, ler, editar e converter arquivos Word em aplicativos Python. Ele fornece suporte perfeito para vários formatos do Word, incluindo Doc, Docx, Docm, Dot, Dotx, Dotm e muito mais. Além disso, permite a conversão de alta qualidade de documentos do Word para diferentes formatos, como Word para PDF, Word para RTF, Word para HTML, Word para Text, e Word para Image.

Para instalar o Spire.Doc for Python, você pode executar o seguinte comando pip:

pip install Spire.Doc

Para obter instruções detalhadas de instalação, consulte esta documentação: Como instalar o Spire.Doc for Python no VS Code.

Crie documentos do Word a partir de modelos substituindo texto de espaço reservado em Python

"Texto de espaço reservado" refere-se ao texto temporário que pode ser facilmente substituído pelo conteúdo desejado. Para criar um documento do Word a partir de um modelo substituindo o texto do espaço reservado, você precisa preparar um modelo que inclua texto do espaço reservado predefinido. Este modelo pode ser criado manualmente usando o aplicativo Microsoft Word ou gerado programaticamente com Spire.Doc for Python.

Aqui estão as etapas para criar um documento do Word a partir de um modelo, substituindo o texto do espaço reservado usando Spire.Doc for Python:

  • Crie uma instância de Document e carregue um modelo do Word usando o método Document.LoadFromFile().
  • Defina um dicionário que mapeie o texto do espaço reservado para o texto de substituição correspondente para realizar substituições no documento.
  • Percorra o dicionário.
  • Substitua o texto do espaço reservado no documento pelo texto de substituição correspondente usando o método Document.Replace().
  • Salve o documento resultante usando o método Document.SaveToFile().

Aqui está um exemplo de código que cria um documento do Word a partir de um modelo substituindo o texto do espaço reservado usando Spire.Doc for Python:

  • Python
from spire.doc import *
from spire.doc.common import *

# Specify the input and output file paths
inputFile = "Placeholder_Template.docx"
outputFile = "CreateDocumentByReplacingPlaceholderText.docx"

# Create a Document object
document = Document()
# Load a Word template with placeholder text
document.LoadFromFile(inputFile)

# Create a dictionary to store the placeholder text and its corresponding replacement text
# Each key represents a placeholder, while the corresponding value represents the replacement text
text_replacements = {
    "{name}": "John Smith",
    "{email}": "johnsmith@example.com",
    "{telephone}": "(123) 456-7890",
    "{address}": "123 Main Street, A City, B State",
    "{education}": "B.S. in Computer Science \nXYZ University \n2010 - 2014",
    "{experience}": "Software Engineer \nABC Company \n2015 - Present",
    "{skills}": "Programming (Python, Java, C++) \nProject Management \nProblem Solving",
    "{projects}": "Developed a mobile app for XYZ Company, resulting in a 20% increase in user engagement. \nLed a team of 5 developers to successfully deliver a complex software project on time and within budget.",
    "{certifications}": "Project Management Professional (PMP) \nMicrosoft Certified: Azure Developer Associate",
    "{languages}": "English (Fluent) \nSpanish (Intermediate)",
    "{interests}": "Traveling, Photography, Reading"
}

# Loop through the dictionary
for placeholder_text, replacement_text in text_replacements.items():
    # Replace the placeholder text in the document with the replacement text
    document.Replace(placeholder_text, replacement_text, False, False)

# Save the resulting document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Dicas: Este exemplo explicou como substituir o texto do espaço reservado em um modelo do Word por um novo texto. É importante notar que Spire.Doc para Python oferece suporte à substituição de texto em vários cenários, incluindo substituição de texto por imagens, substituição de texto por tabelas, substituição de texto usando regex e muito mais. Você pode encontrar mais detalhes nesta documentação: Python: encontre e substitua texto no Word.

Crie documentos do Word a partir de modelos substituindo marcadores em Python

Os marcadores em um documento do Word servem como pontos de referência que permitem inserir ou substituir conteúdo com precisão em locais específicos do documento. Para criar um documento do Word a partir de um modelo substituindo marcadores, você precisa preparar um modelo que contenha marcadores predefinidos. Este modelo pode ser criado manualmente usando o aplicativo Microsoft Word ou gerado programaticamente com Spire.Doc for Python.

Aqui estão as etapas para criar um documento do Word a partir de um modelo substituindo marcadores usando Spire.Doc for Python:

  • Crie uma instância de Document e carregue um documento do Word usando o método Document.LoadFromFile().
  • Defina um dicionário que mapeie nomes de marcadores para seu texto de substituição correspondente para realizar substituições no documento.
  • Percorra o dicionário.
  • Crie uma instância de BookmarksNavigator e navegue até o marcador específico por seu nome usando o método BookmarkNavigator.MoveToBookmark().
  • Substitua o conteúdo do marcador pelo texto de substituição correspondente usando o método BookmarkNavigator.ReplaceBookmarkContent().
  • Salve o documento resultante usando o método Document.SaveToFile().

Aqui está um exemplo de código que cria um documento do Word a partir de um modelo substituindo marcadores usando Spire.Doc for Python:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word template with bookmarks
document.LoadFromFile("Template_Bookmark.docx")

# Create a dictionary to store the bookmark names and their corresponding replacement text
# Each key represents a bookmark name, while the corresponding value represents the replacement text
bookmark_replacements = {
    "introduction": "In today's digital age, effective communication is crucial.",
    "methodology": "Our research approach focuses on gathering qualitative data.",
    "results": "The analysis reveals significant findings supporting our hypothesis.",
    "conclusion": "Based on our findings, we recommend further investigation in this field."
}

# Loop through the dictionary
for bookmark_name, replacement_text in bookmark_replacements.items():
    # Replace the content of the bookmarks in the document with the corresponding replacement text
    bookmarkNavigator = BookmarksNavigator(document)
    bookmarkNavigator.MoveToBookmark(bookmark_name)
    bookmarkNavigator.ReplaceBookmarkContent(replacement_text, True)
    # Remove the bookmarks from the document
    document.Bookmarks.Remove(bookmarkNavigator.CurrentBookmark)

# Save the resulting document
document.SaveToFile("CreateDocumentByReplacingBookmark.docx", FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Crie documentos do Word a partir de modelos realizando mala direta em Python

A mala direta é um recurso poderoso do Microsoft Word que permite criar documentos personalizados a partir de um modelo, mesclando-o com uma fonte de dados. Para criar um documento do Word a partir de um modelo realizando mala direta, você precisa preparar um modelo que inclua campos de mesclagem predefinidos. Este modelo pode ser criado manualmente usando o aplicativo Microsoft Word ou gerado programaticamente com Spire.Doc for Python usando o seguinte código:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Add a section
section = document.AddSection()
# Set page margins
section.PageSetup.Margins.All = 72.0

# Add a paragraph
paragraph = section.AddParagraph()
# Add text to the paragraph
paragraph.AppendText("Customer Name: ")

# Add a paragraph
paragraph = section.AddParagraph()
# Add a merge field to the paragraph
paragraph.AppendField("Recipient Name", FieldType.FieldMergeField)

# Save the resulting document
document.SaveToFile("Template.docx", FileFormat.Docx2013)
document.Close()

Aqui estão as etapas para criar um documento do Word a partir de um modelo realizando mala direta usando Spire.Doc for Python:

  • Crie uma instância de Document e carregue um modelo do Word usando o método Document.LoadFromFile().
  • Defina uma lista de nomes de campos de mesclagem.
  • Defina uma lista de valores de campo de mesclagem.
  • Execute uma mala direta usando os nomes e valores de campo especificados usando o método Document.MailMerge.Execute().
  • Salve o documento resultante usando o método Document.SaveToFile().

Aqui está um exemplo de código que cria um documento do Word a partir de um modelo realizando mala direta usando Spire.Doc for Python:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word template with merge fields
document.LoadFromFile("Template_MergeFields.docx")

# Define a list of field names
filedNames = ["Recipient Name", "Company Name", "Amount", "Due Date", "Payment Method", "Sender Name", "Title", "Phone"]

# Define a list of field values
filedValues = ["John Smith",  "ABC Company", "$500", DateTime.get_Now().Date.ToString(), "PayPal", "Sarah Johnson", "Accounts Receivable Manager", "123-456-7890"]

# Perform a mail merge operation using the specified field names and field values
document.MailMerge.Execute(filedNames, filedValues)

# Save the resulting document
document.SaveToFile("CreateDocumentByMailMerge.docx", FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Obtenha uma licença gratuita

Para experimentar totalmente os recursos do Spire.Doc for Python sem quaisquer limitações de avaliação, você pode solicitar uma licença de teste gratuita de 30 dias.

Conclusão

Este blog demonstrou como criar documentos do Word a partir de modelos de 3 maneiras diferentes usando Python e Spire.Doc for Python. Além de criar documentos Word, Spire.Doc for Python oferece inúmeros recursos para manipulação de documentos Word, você pode verificar seu documentação Para maiores informações. Se você encontrar alguma dúvida, sinta-se à vontade para publicá-la em nosso fórum ou envie-os para nossa equipe de suporte via e-mail.

Veja também

Шаблоны предоставляют готовую структуру и макет, что экономит ваше время и усилия при создании документов с нуля. Вместо того, чтобы разрабатывать макет документа, стили форматирования и организацию разделов, вы можете просто выбрать шаблон, соответствующий вашим требованиям, и начать добавлять свой контент. Это особенно полезно, когда вам нужно создать несколько документов с единообразным внешним видом. В этом блоге мы рассмотрим, как создавать документы Word из шаблонов с помощью Python.

Мы обсудим три различных подхода к созданию документов Word из шаблонов:

Библиотека Python для создания документов Word из шаблонов

Для начала нам необходимо установить необходимый модуль Python, поддерживающий генерацию документов Word из шаблонов. В этом сообщении блога мы будем использовать библиотеку Spire.Doc for Python .

Spire.Doc for Python предлагает полный набор функций для создания, чтения, редактирования и преобразования файлов Word в приложениях Python. Он обеспечивает бесперебойную поддержку различных форматов Word, включая Doc, Docx, Docm, Dot, Dotx, Dotm и другие. Кроме того, он обеспечивает высококачественное преобразование документов Word в различные форматы, такие как Word в PDF, Word в RTF, Word в HTML, Word в текст и Word в изображение.

Чтобы установить Spire.Doc for Python, вы можете запустить следующую команду pip:

pip install Spire.Doc

Подробные инструкции по установке можно найти в этой документации: Как установить Spire.Doc for Python в VS Code.

Создание документов Word из шаблонов путем замены текста заполнителя в Python

«Текст-заполнитель» относится к временному тексту, который можно легко заменить нужным содержимым. Чтобы создать документ Word на основе шаблона путем замены текста-заполнителя, необходимо подготовить шаблон, включающий предварительно определенный текст-заполнитель. Этот шаблон можно создать вручную с помощью приложения Microsoft Word или программно сгенерированный с помощью Spire.Doc for Python.

Ниже приведены шаги по созданию документа Word на основе шаблона путем замены текста-заполнителя с помощью Spire.Doc for Python:

  • Создайте экземпляр документа, а затем загрузите шаблон Word с помощью метода Document.LoadFromFile().
  • Определите словарь, который сопоставляет текст-заполнитель с соответствующим текстом замены для выполнения замен в документе.
  • Пролистайте словарь.
  • Замените текст заполнителя в документе соответствующим текстом замены, используя метод Document.Replace().
  • Сохраните полученный документ с помощью метода Document.SaveToFile().

Ниже приведен пример кода, который создает документ Word из шаблона путем замены текста-заполнителя с помощью Spire.Doc for Python:

  • Python
from spire.doc import *
from spire.doc.common import *

# Specify the input and output file paths
inputFile = "Placeholder_Template.docx"
outputFile = "CreateDocumentByReplacingPlaceholderText.docx"

# Create a Document object
document = Document()
# Load a Word template with placeholder text
document.LoadFromFile(inputFile)

# Create a dictionary to store the placeholder text and its corresponding replacement text
# Each key represents a placeholder, while the corresponding value represents the replacement text
text_replacements = {
    "{name}": "John Smith",
    "{email}": "johnsmith@example.com",
    "{telephone}": "(123) 456-7890",
    "{address}": "123 Main Street, A City, B State",
    "{education}": "B.S. in Computer Science \nXYZ University \n2010 - 2014",
    "{experience}": "Software Engineer \nABC Company \n2015 - Present",
    "{skills}": "Programming (Python, Java, C++) \nProject Management \nProblem Solving",
    "{projects}": "Developed a mobile app for XYZ Company, resulting in a 20% increase in user engagement. \nLed a team of 5 developers to successfully deliver a complex software project on time and within budget.",
    "{certifications}": "Project Management Professional (PMP) \nMicrosoft Certified: Azure Developer Associate",
    "{languages}": "English (Fluent) \nSpanish (Intermediate)",
    "{interests}": "Traveling, Photography, Reading"
}

# Loop through the dictionary
for placeholder_text, replacement_text in text_replacements.items():
    # Replace the placeholder text in the document with the replacement text
    document.Replace(placeholder_text, replacement_text, False, False)

# Save the resulting document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Советы. В этом примере объясняется, как заменить текст-заполнитель в шаблоне Word новым текстом. Стоит отметить, что Spire.Doc для Python поддерживает замену текста в различных сценариях, включая замену текста изображениями, замену текста таблицами, замену текста с помощью регулярных выражений и многое другое. Более подробную информацию можно найти в этой документации: Python: найти и заменить текст в Word.

Создание документов Word из шаблонов путем замены закладок в Python

Закладки в документе Word служат ориентирами, которые позволяют точно вставлять или заменять контент в определенных местах документа. Чтобы создать документ Word из шаблона путем замены закладок, необходимо подготовить шаблон, содержащий предопределенные закладки. Этот шаблон можно создать вручную с помощью приложения Microsoft Word или программно сгенерированный с помощью Spire.Doc for Python.

Ниже приведены шаги по созданию документа Word из шаблона путем замены закладок с помощью Spire.Doc for Python:

  • Создайте экземпляр Document и загрузите документ Word с помощью метода Document.LoadFromFile().
  • Определите словарь, который сопоставляет имена закладок с соответствующим текстом замены для выполнения замен в документе.
  • Пролистайте словарь.
  • Создайте экземпляр BookmarksNavigator и перейдите к определенной закладке по ее имени с помощью метода BookmarkNavigator.MoveToBookmark().
  • Замените содержимое закладки соответствующим текстом замены, используя метод BookmarkNavigator.ReplaceBookmarkContent().
  • Сохраните полученный документ с помощью метода Document.SaveToFile().

Ниже приведен пример кода, который создает документ Word из шаблона путем замены закладок с помощью Spire.Doc for Python:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word template with bookmarks
document.LoadFromFile("Template_Bookmark.docx")

# Create a dictionary to store the bookmark names and their corresponding replacement text
# Each key represents a bookmark name, while the corresponding value represents the replacement text
bookmark_replacements = {
    "introduction": "In today's digital age, effective communication is crucial.",
    "methodology": "Our research approach focuses on gathering qualitative data.",
    "results": "The analysis reveals significant findings supporting our hypothesis.",
    "conclusion": "Based on our findings, we recommend further investigation in this field."
}

# Loop through the dictionary
for bookmark_name, replacement_text in bookmark_replacements.items():
    # Replace the content of the bookmarks in the document with the corresponding replacement text
    bookmarkNavigator = BookmarksNavigator(document)
    bookmarkNavigator.MoveToBookmark(bookmark_name)
    bookmarkNavigator.ReplaceBookmarkContent(replacement_text, True)
    # Remove the bookmarks from the document
    document.Bookmarks.Remove(bookmarkNavigator.CurrentBookmark)

# Save the resulting document
document.SaveToFile("CreateDocumentByReplacingBookmark.docx", FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Создавайте документы Word из шаблонов, выполняя слияние почты в Python

Слияние почты — это мощная функция Microsoft Word, которая позволяет создавать настраиваемые документы на основе шаблона, объединяя его с источником данных. Чтобы создать документ Word на основе шаблона путем выполнения слияния почты, необходимо подготовить шаблон, включающий предопределенные поля слияния. Этот шаблон можно создать вручную с помощью приложения Microsoft Word или программно с помощью Spire.Doc for Python, используя следующий код:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Add a section
section = document.AddSection()
# Set page margins
section.PageSetup.Margins.All = 72.0

# Add a paragraph
paragraph = section.AddParagraph()
# Add text to the paragraph
paragraph.AppendText("Customer Name: ")

# Add a paragraph
paragraph = section.AddParagraph()
# Add a merge field to the paragraph
paragraph.AppendField("Recipient Name", FieldType.FieldMergeField)

# Save the resulting document
document.SaveToFile("Template.docx", FileFormat.Docx2013)
document.Close()

Ниже приведены шаги по созданию документа Word из шаблона путем выполнения слияния почты с помощью Spire.Doc for Python:

  • Создайте экземпляр документа, а затем загрузите шаблон Word с помощью метода Document.LoadFromFile().
  • Определите список имен полей слияния.
  • Определите список значений поля слияния.
  • Выполните слияние почты, используя указанные имена полей и значения полей, используя метод Document.MailMerge.Execute().
  • Сохраните полученный документ с помощью метода Document.SaveToFile().

Ниже приведен пример кода, который создает документ Word из шаблона путем выполнения слияния почты с помощью Spire.Doc for Python:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word template with merge fields
document.LoadFromFile("Template_MergeFields.docx")

# Define a list of field names
filedNames = ["Recipient Name", "Company Name", "Amount", "Due Date", "Payment Method", "Sender Name", "Title", "Phone"]

# Define a list of field values
filedValues = ["John Smith",  "ABC Company", "$500", DateTime.get_Now().Date.ToString(), "PayPal", "Sarah Johnson", "Accounts Receivable Manager", "123-456-7890"]

# Perform a mail merge operation using the specified field names and field values
document.MailMerge.Execute(filedNames, filedValues)

# Save the resulting document
document.SaveToFile("CreateDocumentByMailMerge.docx", FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Получите бесплатную лицензию

Чтобы в полной мере оценить возможности Spire.Doc for Python без каких-либо ограничений оценки, вы можете запросить бесплатная 30-дневная пробная лицензия.

Заключение

В этом блоге показано, как создавать документы Word из шаблонов тремя различными способами с использованием Python и Spire.Doc for Python. Помимо создания документов Word, Spire.Doc for Python предоставляет множество функций для работы с документами Word. Дополнительную информацию можно найти в его документации. Если у вас возникнут какие-либо вопросы, пожалуйста, задайте их на нашем сайте. Форум или отправьте их в нашу службу поддержки через электронная почта.

Смотрите также

Vorlagen bieten eine vorgefertigte Struktur und ein vorgefertigtes Layout, wodurch Sie Zeit und Aufwand bei der Erstellung von Dokumenten von Grund auf sparen. Anstatt das Dokumentlayout, die Formatierungsstile und die Abschnittsorganisation zu entwerfen, können Sie einfach eine Vorlage auswählen, die Ihren Anforderungen entspricht, und mit dem Hinzufügen Ihrer Inhalte beginnen. Dies ist besonders nützlich, wenn Sie mehrere Dokumente mit einem einheitlichen Erscheinungsbild erstellen müssen. In diesem Blog erfahren Sie, wie das geht Erstellen Sie Word-Dokumente aus Vorlagen mit Python.

Wir werden drei verschiedene Ansätze zur Generierung von Word-Dokumenten aus Vorlagen diskutieren:

Python-Bibliothek zum Erstellen von Word-Dokumenten aus Vorlagen

Zunächst müssen wir das erforderliche Python-Modul installieren, das die Erstellung von Word-Dokumenten aus Vorlagen unterstützt. In diesem Blogbeitrag verwenden wir die Bibliothek Spire.Doc for Python.

Spire.Doc for Python bietet umfassende Funktionen zum Erstellen, Lesen, Bearbeiten und Konvertieren von Word-Dateien in Python-Anwendungen. Es bietet nahtlose Unterstützung für verschiedene Word-Formate, darunter Doc, Docx, Docm, Dot, Dotx, Dotm und mehr. Darüber hinaus ermöglicht es die hochwertige Konvertierung von Word-Dokumenten in verschiedene Formate, z. B. Word in PDF, Word in RTF, Word in HTML, Word in Text, und Word in Image.

Um Spire.Doc for Python zu installieren, können Sie den folgenden pip-Befehl ausführen:

pip install Spire.Doc

Detaillierte Installationsanweisungen finden Sie in dieser Dokumentation: So installieren Sie Spire.Doc for Python in VS Code..

Erstellen Sie Word-Dokumente aus Vorlagen, indem Sie Platzhaltertext in Python ersetzen

„Platzhaltertext“ bezeichnet temporären Text, der einfach durch den gewünschten Inhalt ersetzt werden kann. Um ein Word-Dokument aus einer Vorlage durch Ersetzen von Platzhaltertext zu erstellen, müssen Sie eine Vorlage vorbereiten, die vordefinierten Platzhaltertext enthält. Diese Vorlage kann manuell mit der Microsoft Word-Anwendung erstellt werden oder programmgesteuert generiert mit Spire.Doc for Python.

Hier sind die Schritte zum Erstellen eines Word-Dokuments aus einer Vorlage durch Ersetzen von Platzhaltertext mit Spire.Doc for Python:

  • Erstellen Sie eine Document-Instanz und laden Sie dann eine Word-Vorlage mit der Methode Document.LoadFromFile().
  • Definieren Sie ein Wörterbuch, das Platzhaltertext dem entsprechenden Ersetzungstext zuordnet, um Ersetzungen im Dokument durchzuführen.
  • Gehen Sie das Wörterbuch durc
  • Ersetzen Sie den Platzhaltertext im Dokument mit der Document.Replace()-Methode durch den entsprechenden Ersatztext.
  • Speichern Sie das resultierende Dokument mit der Methode Document.SaveToFile().

Hier ist ein Codebeispiel, das ein Word-Dokument aus einer Vorlage erstellt, indem Platzhaltertext mit Spire.Doc for Python ersetzt wird:

  • Python
from spire.doc import *
from spire.doc.common import *

# Specify the input and output file paths
inputFile = "Placeholder_Template.docx"
outputFile = "CreateDocumentByReplacingPlaceholderText.docx"

# Create a Document object
document = Document()
# Load a Word template with placeholder text
document.LoadFromFile(inputFile)

# Create a dictionary to store the placeholder text and its corresponding replacement text
# Each key represents a placeholder, while the corresponding value represents the replacement text
text_replacements = {
    "{name}": "John Smith",
    "{email}": "johnsmith@example.com",
    "{telephone}": "(123) 456-7890",
    "{address}": "123 Main Street, A City, B State",
    "{education}": "B.S. in Computer Science \nXYZ University \n2010 - 2014",
    "{experience}": "Software Engineer \nABC Company \n2015 - Present",
    "{skills}": "Programming (Python, Java, C++) \nProject Management \nProblem Solving",
    "{projects}": "Developed a mobile app for XYZ Company, resulting in a 20% increase in user engagement. \nLed a team of 5 developers to successfully deliver a complex software project on time and within budget.",
    "{certifications}": "Project Management Professional (PMP) \nMicrosoft Certified: Azure Developer Associate",
    "{languages}": "English (Fluent) \nSpanish (Intermediate)",
    "{interests}": "Traveling, Photography, Reading"
}

# Loop through the dictionary
for placeholder_text, replacement_text in text_replacements.items():
    # Replace the placeholder text in the document with the replacement text
    document.Replace(placeholder_text, replacement_text, False, False)

# Save the resulting document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Tipps: In diesem Beispiel wurde erläutert, wie Sie Platzhaltertext in einer Word-Vorlage durch neuen Text ersetzen. Es ist erwähnenswert, dass Spire.Doc für Python das Ersetzen von Text in verschiedenen Szenarien unterstützt, darunter das Ersetzen von Text durch Bilder, das Ersetzen von Text durch Tabellen, das Ersetzen von Text mithilfe von Regex und mehr. Weitere Details finden Sie in dieser Dokumentation: Python: Text in Word suchen und ersetzen.

Erstellen Sie Word-Dokumente aus Vorlagen, indem Sie Lesezeichen in Python ersetzen

Lesezeichen in einem Word-Dokument dienen als Referenzpunkte, die es Ihnen ermöglichen, Inhalte an bestimmten Stellen im Dokument präzise einzufügen oder zu ersetzen. Um ein Word-Dokument aus einer Vorlage durch Ersetzen von Lesezeichen zu erstellen, müssen Sie eine Vorlage vorbereiten, die vordefinierte Lesezeichen enthält. Diese Vorlage kann manuell mit der Microsoft Word-Anwendung erstellt werden oder programmgesteuert generiert mit Spire.Doc for Python.

Hier sind die Schritte zum Erstellen eines Word-Dokuments aus einer Vorlage durch Ersetzen von Lesezeichen mit Spire.Doc for Python:

  • Erstellen Sie eine Document-Instanz und laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Definieren Sie ein Wörterbuch, das Lesezeichennamen dem entsprechenden Ersetzungstext zuordnet, um Ersetzungen im Dokument durchzuführen.
  • Gehen Sie das Wörterbuch durch.
  • Erstellen Sie eine BookmarksNavigator-Instanz und navigieren Sie mit der Methode BookmarkNavigator.MoveToBookmark() anhand seines Namens zum jeweiligen Lesezeichen.
  • Ersetzen Sie den Inhalt des Lesezeichens durch den entsprechenden Ersatztext mithilfe der Methode BookmarkNavigator.ReplaceBookmarkContent().
  • Speichern Sie das resultierende Dokument mit der Methode Document.SaveToFile().

Hier ist ein Codebeispiel, das ein Word-Dokument aus einer Vorlage erstellt, indem Lesezeichen mithilfe von Spire.Doc for Python ersetzt werden:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word template with bookmarks
document.LoadFromFile("Template_Bookmark.docx")

# Create a dictionary to store the bookmark names and their corresponding replacement text
# Each key represents a bookmark name, while the corresponding value represents the replacement text
bookmark_replacements = {
    "introduction": "In today's digital age, effective communication is crucial.",
    "methodology": "Our research approach focuses on gathering qualitative data.",
    "results": "The analysis reveals significant findings supporting our hypothesis.",
    "conclusion": "Based on our findings, we recommend further investigation in this field."
}

# Loop through the dictionary
for bookmark_name, replacement_text in bookmark_replacements.items():
    # Replace the content of the bookmarks in the document with the corresponding replacement text
    bookmarkNavigator = BookmarksNavigator(document)
    bookmarkNavigator.MoveToBookmark(bookmark_name)
    bookmarkNavigator.ReplaceBookmarkContent(replacement_text, True)
    # Remove the bookmarks from the document
    document.Bookmarks.Remove(bookmarkNavigator.CurrentBookmark)

# Save the resulting document
document.SaveToFile("CreateDocumentByReplacingBookmark.docx", FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Erstellen Sie Word-Dokumente aus Vorlagen, indem Sie einen Seriendruck in Python durchführen

Seriendruck ist eine leistungsstarke Funktion in Microsoft Word, mit der Sie benutzerdefinierte Dokumente aus einer Vorlage erstellen können, indem Sie diese mit einer Datenquelle zusammenführen. Um ein Word-Dokument aus einer Vorlage durch einen Serienbrief zu erstellen, müssen Sie eine Vorlage vorbereiten, die vordefinierte Serienbrieffelder enthält. Diese Vorlage kann manuell mit der Microsoft Word-Anwendung erstellt oder programmgesteuert mit Spire.Doc for Python mithilfe des folgenden Codes generiert werden:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Add a section
section = document.AddSection()
# Set page margins
section.PageSetup.Margins.All = 72.0

# Add a paragraph
paragraph = section.AddParagraph()
# Add text to the paragraph
paragraph.AppendText("Customer Name: ")

# Add a paragraph
paragraph = section.AddParagraph()
# Add a merge field to the paragraph
paragraph.AppendField("Recipient Name", FieldType.FieldMergeField)

# Save the resulting document
document.SaveToFile("Template.docx", FileFormat.Docx2013)
document.Close()

Hier sind die Schritte zum Erstellen eines Word-Dokuments aus einer Vorlage durch Durchführen eines Seriendrucks mit Spire.Doc for Python:

  • Erstellen Sie eine Document-Instanz und laden Sie dann eine Word-Vorlage mit der Methode Document.LoadFromFile().
  • Definieren Sie eine Liste mit Zusammenführungsfeldnamen.
  • Definieren Sie eine Liste von Zusammenführungsfeldwerten.
  • Führen Sie einen Serienbrief mit den angegebenen Feldnamen und Feldwerten mithilfe der Methode Document.MailMerge.Execute() durch.
  • Speichern Sie das resultierende Dokument mit der Methode Document.SaveToFile().

Hier ist ein Codebeispiel, das ein Word-Dokument aus einer Vorlage erstellt, indem es einen Serienbrief mit Spire.Doc for Python durchführt:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()
# Load a Word template with merge fields
document.LoadFromFile("Template_MergeFields.docx")

# Define a list of field names
filedNames = ["Recipient Name", "Company Name", "Amount", "Due Date", "Payment Method", "Sender Name", "Title", "Phone"]

# Define a list of field values
filedValues = ["John Smith",  "ABC Company", "$500", DateTime.get_Now().Date.ToString(), "PayPal", "Sarah Johnson", "Accounts Receivable Manager", "123-456-7890"]

# Perform a mail merge operation using the specified field names and field values
document.MailMerge.Execute(filedNames, filedValues)

# Save the resulting document
document.SaveToFile("CreateDocumentByMailMerge.docx", FileFormat.Docx2016)
document.Close()

Create Word Documents from Templates with Python

Holen Sie sich eine kostenlose Lizenz

Um die Funktionen von Spire.Doc for Python ohne jegliche Evaluierungseinschränkungen voll auszuschöpfen, können Sie eine Anfrage stellen eine kostenlose 30-Tage-Testlizenz.

Abschluss

In diesem Blog wurde gezeigt, wie Sie mit Python und Spire.Doc for Python auf drei verschiedene Arten Word-Dokumente aus Vorlagen erstellen können. Zusätzlich zum Erstellen von Word-Dokumenten bietet Spire.Doc for Python zahlreiche Funktionen zum Bearbeiten von Word-Dokumenten. Sie können die Dokumentation überprüfen für mehr Informationen. Wenn Sie Fragen haben, können Sie diese gerne in unserem Forum posten oder per E-Mail an unser Support-Team senden.

Siehe auch