Текстовые файлы — это распространенный тип файлов, который содержит только простой текст без какого-либо форматирования или стилей. Если вы хотите применить форматирование или добавить изображения, диаграммы, таблицы и другие элементы мультимедиа в текстовые файлы, одним из рекомендуемых решений является преобразование их в файлы Word.

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

Установите Spire.Doc for Python

Для этого сценария требуется Spire.Doc for Python и Plum-Dispatch v1.7.4. Их можно легко установить в ваш VS Code с помощью следующих команд pip.

pip install Spire.Doc

Если вы не знаете, как установить, обратитесь к этому руководству: Как установить Spire.Doc for Python в VS Code.

Преобразование текста (TXT) в Word на Python

Преобразование из TXT в Word довольно простое и требует всего лишь нескольких строк кода. Ниже приведены подробные шаги.

  • Создайте объект Документ.
  • Загрузите текстовый файл с помощью метода Document.LoadFromFile(string fileName).
  • Сохраните текстовый файл как файл Word, используя метод Document.SaveToFile(string fileName, FileFormat fileFormat).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Преобразование слова в текст (TXT) в Python

Метод Document.SaveToFile(string fileName, FileFormat.Txt), предоставляемый Spire.Doc for Python, позволяет экспортировать файл Word в текстовый формат. Ниже приведены подробные шаги.

  • Создайте объект Документ.
  • Загрузите файл Word с помощью метода Document.LoadFromFile(string fileName).
  • Сохраните файл Word в формате txt, используя метод Document.SaveToFile(string fileName, FileFormat.Txt).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

Подать заявку на временную лицензию

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

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

Textdateien sind ein gängiger Dateityp, der nur einfachen Text ohne jegliche Formatierung oder Stile enthält. Wenn Sie Textdateien formatieren oder Bilder, Diagramme, Tabellen und andere Medienelemente hinzufügen möchten, besteht eine der empfohlenen Lösungen darin, sie in Word-Dateien zu konvertieren.

Wenn Sie umgekehrt Inhalte effizient extrahieren oder die Dateigröße von Word-Dokumenten reduzieren möchten, können Sie diese in das Textformat konvertieren. In diesem Artikel wird die programmgesteuerte Vorgehensweise demonstriert Konvertieren Sie Textdateien in das Word-Format und konvertieren Sie Word-Dateien in das Textformat mit Spire.Doc for Python.

Installieren Sie Spire.Doc for Python

Dieses Szenario erfordert Spire.Doc for Python und plum-dispatch v1.7.4. Sie können mit den folgenden Pip-Befehlen einfach in Ihrem VS-Code installiert werden.

pip install Spire.Doc

Wenn Sie sich bei der Installation nicht sicher sind, lesen Sie bitte dieses Tutorial: So installieren Sie Spire.Doc for Python in VS Code

Konvertieren Sie Text (TXT) in Word in Python

Die Konvertierung von TXT nach Word ist recht einfach und erfordert nur wenige Codezeilen. Im Folgenden finden Sie die detaillierten Schritte.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie eine Textdatei mit der Methode Document.LoadFromFile(string fileName).
  • Speichern Sie die Textdatei mit der Methode Document.SaveToFile(string fileName, FileFormat fileFormat) als Word-Datei.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Konvertieren Sie Word in Text (TXT) in Python

Mit der von Spire.Doc for Python bereitgestellten Methode Document.SaveToFile(string fileName, FileFormat.Txt) können Sie eine Word-Datei in das Textformat exportieren. Im Folgenden finden Sie die detaillierten Schritte.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie eine Word-Datei mit der Methode Document.LoadFromFile(string fileName).
  • Speichern Sie die Word-Datei im TXT-Format mit der Methode Document.SaveToFile(string fileName, FileFormat.Txt).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Instalar con Pip

pip install Spire.Doc

enlaces relacionados

Los archivos de texto son un tipo de archivo común que contiene solo texto sin formato sin ningún formato ni estilo. Si desea aplicar formato o agregar imágenes, gráficos, tablas y otros elementos multimedia a archivos de texto, una de las soluciones recomendadas es convertirlos a archivos de Word.

Por el contrario, si desea extraer contenido de manera eficiente o reducir el tamaño de archivo de documentos de Word, puede convertirlos a formato de texto. Este artículo demostrará cómo programar convierta archivos de texto a formato Word y convierta archivos de Word a formato de texto usando Spire.Doc for Python.

Instalar Spire.Doc for Python

Este escenario requiere Spire.Doc for Python y plum-dispatch v1.7.4. Se pueden instalar fácilmente en su código VS mediante los siguientes comandos pip.

pip install Spire.Doc

Si no está seguro de cómo instalarlo, consulte este tutorial: Cómo instalar Spire.Doc for Python en VS Code

Convertir texto (TXT) a Word en Python

La conversión de TXT a Word es bastante simple y requiere sólo unas pocas líneas de código. Los siguientes son los pasos detallados.

  • Crea un objeto de documento.
  • Cargue un archivo de texto utilizando el método Document.LoadFromFile(string fileName).
  • Guarde el archivo de texto como un archivo de Word utilizando el método Document.SaveToFile(string fileName, FileFormat fileFormat).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Convertir palabra a texto (TXT) en Python

El método Document.SaveToFile(string fileName, FileFormat.Txt) proporcionado por Spire.Doc for Python le permite exportar un archivo de Word a formato de texto. Los siguientes son los pasos detallados.

  • Crea un objeto de documento.
  • Cargue un archivo de Word utilizando el método Document.LoadFromFile (nombre de archivo de cadena).
  • Guarde el archivo de Word en formato txt utilizando el método Document.SaveToFile(string fileName, FileFormat.Txt).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

Solicitar una licencia temporal

Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.

Ver también

텍스트 파일은 서식이나 스타일 없이 일반 텍스트만 포함하는 일반적인 파일 형식입니다. 텍스트 파일에 서식을 적용하거나 이미지, 차트, 표 및 기타 미디어 요소를 추가하려는 경우 권장되는 해결 방법 중 하나는 해당 텍스트를 Word 파일로 변환하는 것입니다.

반대로 콘텐츠를 효율적으로 추출하고 싶거나 Word 문서의 파일 크기를 줄이고 싶다면 텍스트 형식으로 변환하면 됩니다. 이 문서에서는 프로그래밍 방식으로 방법을 보여줍니다 텍스트 파일을 Word 형식으로 변환 그리고 Word 파일을 텍스트 형식으로 변환 Spire.Doc for Python 사용합니다.

Spire.Doc for Python 설치

이 시나리오에는 Spire.Doc for Python 및 Plum-dispatch v1.7.4가 필요합니다. 다음 pip 명령을 통해 VS Code에 쉽게 설치할 수 있습니다.

pip install Spire.Doc

설치 방법을 잘 모르는 경우 다음 튜토리얼을 참조하세요: VS Code에서 Spire.Doc for Python 설치하는 방법

Python에서 텍스트(TXT)를 Word로 변환

TXT에서 Word로의 변환은 몇 줄의 코드만 있으면 매우 간단합니다. 자세한 단계는 다음과 같습니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile(string fileName) 메서드를 사용하여 텍스트 파일을 로드합니다.
  • Document.SaveToFile(string fileName, FileFormat fileFormat) 메서드를 사용하여 텍스트 파일을 Word 파일로 저장합니다.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Python에서 Word를 텍스트(TXT)로 변환

Spire.Doc for Python에서 제공하는 Document.SaveToFile(string fileName, FileFormat.Txt) 메서드를 사용하면 Word 파일을 텍스트 형식으로 내보낼 수 있습니다. 자세한 단계는 다음과 같습니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile(string fileName) 메서드를 사용하여 Word 파일을 로드합니다.
  • Document.SaveToFile(string fileName, FileFormat.Txt) 메서드를 사용하여 Word 파일을 txt 형식으로 저장합니다.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

I file di testo sono un tipo di file comune che contiene solo testo semplice senza formattazione o stili. Se desideri applicare la formattazione o aggiungere immagini, grafici, tabelle e altri elementi multimediali ai file di testo, una delle soluzioni consigliate è convertirli in file Word.

Al contrario, se desideri estrarre contenuti in modo efficiente o ridurre le dimensioni dei file dei documenti Word, puoi convertirli in formato testo. Questo articolo dimostrerà come farlo a livello di codice convertire file di testo in formato Word e convertire file di Word in formato testo utilizzando Spire.Doc for Python.

Installa Spire.Doc for Python

Questo scenario richiede Spire.Doc for Python e plum-dispatch v1.7.4. Possono essere facilmente installati nel tuo VS Code tramite i seguenti comandi pip.

pip install Spire.Doc

Se non sei sicuro su come installare, fai riferimento a questo tutorial: Come installare Spire.Doc for Python in VS Code

Converti testo (TXT) in Word in Python

La conversione da TXT a Word è abbastanza semplice e richiede solo poche righe di codice. Di seguito sono riportati i passaggi dettagliati.

  • Creare un oggetto Documento.
  • Carica un file di testo utilizzando il metodo Document.LoadFromFile(string fileName).
  • Salvare il file di testo come file Word utilizzando il metodo Document.SaveToFile(string fileName, FileFormat fileFormat).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Converti Word in testo (TXT) in Python

Il metodo Document.SaveToFile(string fileName, FileFormat.Txt) fornito da Spire.Doc for Python consente di esportare un file Word in formato testo. Di seguito sono riportati i passaggi dettagliati.

  • Creare un oggetto Documento.
  • Carica un file Word utilizzando il metodo Document.LoadFromFile(string fileName).
  • Salvare il file Word in formato txt utilizzando il metodo Document.SaveToFile(string fileName, FileFormat.Txt).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Les fichiers texte sont un type de fichier courant qui contient uniquement du texte brut, sans aucun formatage ni style. Si vous souhaitez appliquer une mise en forme ou ajouter des images, des graphiques, des tableaux et d'autres éléments multimédias à des fichiers texte, l'une des solutions recommandées consiste à les convertir en fichiers Word.

À l’inverse, si vous souhaitez extraire efficacement du contenu ou réduire la taille des documents Word, vous pouvez les convertir au format texte. Cet article montrera comment par programmation convertissez des fichiers texte au format Word et convertissez des fichiers Word au format texte à l'aide de Spire.Doc for Python.

Installer Spire.Doc for Python

Ce scénario nécessite Spire.Doc for Python et plum-dispatch v1.7.4. Ils peuvent être facilement installés dans votre VS Code via les commandes pip suivantes.

pip install Spire.Doc

Si vous ne savez pas comment procéder à l'installation, veuillez vous référer à ce didacticiel : Comment installer Spire.Doc for Python dans VS Code

Convertir du texte (TXT) en Word en Python

La conversion de TXT en Word est assez simple et ne nécessite que quelques lignes de code. Voici les étapes détaillées.

  • Créez un objet Document.
  • Chargez un fichier texte à l’aide de la méthode Document.LoadFromFile(string fileName).
  • Enregistrez le fichier texte en tant que fichier Word à l'aide de la méthode Document.SaveToFile(string fileName, FileFormat fileFormat).
  • Python
from spire.doc import *
    from spire.doc.common import *
    
    # Create a Document object
    document = Document()
    
    # Load a TXT file
    document.LoadFromFile("input.txt")
    
    # Save the TXT file as Word
    document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
    document.Close()

Python: Convert Text to Word or Word to Text

Convertir un mot en texte (TXT) en Python

La méthode Document.SaveToFile(string fileName, FileFormat.Txt) fournie par Spire.Doc for Python permet d'exporter un fichier Word au format texte. Voici les étapes détaillées.

  • Créez un objet Document.
  • Chargez un fichier Word à l’aide de la méthode Document.LoadFromFile(string fileName).
  • Enregistrez le fichier Word au format txt à l'aide de la méthode Document.SaveToFile(string fileName, FileFormat.Txt).
  • Python
from spire.doc import *
    from spire.doc.common import *
    
    # Create a Document object
    document = Document()
    
    # Load a Word file from disk
    document.LoadFromFile("Input.docx")
    
    # Save the Word file in txt format
    document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
    document.Close()

Python: Convert Text to Word or Word to Text

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Monday, 18 December 2023 02:34

Python: Convert Word to PDF

Nowadays, digital documents play a significant role in our daily lives, both in personal and professional settings. One such common format is Microsoft Word - used for creating and editing textual documents. However, there may come a time when you need to convert your Word files into a more universally accessible format, such as PDF. PDFs offer advantages like preserving formatting, ensuring compatibility, and maintaining document integrity across different devices and operating systems. In this article, you will learn how to convert Word to PDF in Python using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your VS Code through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python in VS Code

Convert Doc or Docx to PDF in Python

Spire.Doc for Python offers the Document.SaveToFile(string fileName, FileFormat fileFormat) method that allows to save Word as PDF, XPS, HTML, RTF, etc. If you just want to save your Word documents as regular PDFs without additional settings, follow the steps below.

  • Create a Document object.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Save the document to PDF using Doucment.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create word document
document = Document()

# Load a doc or docx file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

#Save the document to PDF
document.SaveToFile("output/ToPDF.pdf", FileFormat.PDF)
document.Close()

Python: Convert Word to PDF

Convert Word to Password-Protected PDF in Python

To convert Word to a Password-Protected PDF, you can utilize the Document.SaveToFile(string fileName, ToPdfParameterList paramList) method, where the ToPdfParameterList parameter allows you to control the conversion process of a Word document into a PDF format. This includes options such as encrypting the document during the conversion. Here are the specific steps to accomplish this task.

  • Create a Document object.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Create a ToPdfParameterList object, which is used to set conversion options.
  • Specify the open password and permission password and then set both passwords for the generated PDF using ToPdfParameterList.PdfSecurity.Encrypt() method.
  • Save the Word document to PDF with password using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parameter = ToPdfParameterList()

# Specify open password and permission password
openPsd = "abc-123"
permissionPsd = "permission"

# Protect the PDF to be generated with open password and permission password
parameter.PdfSecurity.Encrypt(openPsd, permissionPsd, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit)

# Save the Word document to PDF
document.SaveToFile("output/ToPdfWithPassword.pdf", parameter)
document.Close()

Python: Convert Word to PDF

Convert Word to PDF with Bookmarks in Python

Adding bookmarks to a document can improve its readability. When creating PDF from Word, you may want to keep the existing bookmarks or create new ones based on the headings. Here are the steps to convert Word to PDF while maintaining bookmarks.

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile() method.
  • Create a ToPdfParameterList object, which is used to set conversion options.
  • Create bookmarks in PDF from the headings in Word by setting ToPdfParameterList.CreateWordBookmarksUsingHeadings to true.
  • Save the document to PDF with bookmarks using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parames = ToPdfParameterList()

# Create bookmarks from Word headings
parames.CreateWordBookmarksUsingHeadings = True

# Create bookmarks in PDF from existing bookmarks in Word
# parames.CreateWordBookmarks = True

# Save the document to PDF
document.SaveToFile("output/ToPdfWithBookmarks.pdf", FileFormat.PDF)
document.Close()

Python: Convert Word to PDF

Convert Word to PDF with Fonts Embedded in Python

To ensure consistent appearance of a PDF document on any device, you probably need to embed fonts in the generated PDF document. The following are the steps to embed the fonts used in a Word document into the resulting PDF.

  • Create a Document object.
  • Load a sample Word file using Document.LoadFromFile() method.
  • Create a ToPdfParameterList object, which is used to set conversion options.
  • Embed fonts in generated PDF through ToPdfParameterList.IsEmbeddedAllFonts property.
  • Save the document to PDF using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parameter = ToPdfParameterList()

# Embed fonts in PDF
parameter.IsEmbeddedAllFonts = True

# Save the Word document to PDF
document.SaveToFile("output/EmbedFonts.pdf", parameter)
document.Close()

Python: Convert Word to PDF

Set Image Quality When Converting Word to PDF in Python

When converting a Word document to PDF, it is important to consider the size of the resulting file, especially if it contains numerous high-quality images. You have the option to compress the image quality during the conversion process. To do this, follow the steps below.

  • Create a Document object.
  • Load a sample Word file using Document.LoadFromFile() method.
  • Set the image quality through Document.JPEGQuality property.
  • Save the document to PDF using Doucment.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Compress image to 40% of its original quality
document.JPEGQuality = 40

# Preserve original image quality
# document.JPEGQuality = 100

# Save the Word document to PDF
document.SaveToFile("output/SetImageQuality.pdf", FileFormat.PDF)
document.Close()

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

See Also

Monday, 18 December 2023 02:32

Python: Converter Word em PDF

Hoje em dia, os documentos digitais desempenham um papel significativo no nosso quotidiano, tanto no âmbito pessoal como profissional. Um desses formatos comuns é o Microsoft Word – usado para criar e editar documentos textuais. No entanto, pode chegar um momento em que você precisará converter seus arquivos do Word em um formato mais acessível universalmente, como PDF. Os PDFs oferecem vantagens como preservar a formatação, garantir a compatibilidade e manter a integridade dos documentos em diferentes dispositivos e sistemas operacionais. Neste artigo você aprenderá como converter Word para PDF em Python usando Spire.Doc for Python.

Instale Spire.Doc for Python

Este cenário requer Spire.Doc for Python e plum-dispatch v1.7.4. Eles podem ser facilmente instalados em seu VS Code por meio do seguinte comando pip.

pip install Spire.Doc

Se você não tiver certeza de como instalar, consulte este tutorial: Como instalar Spire.Doc for Python no código VS

Converta Doc ou Docx em PDF em Python

Spire.Doc for Python oferece o método Document.SaveToFile(string fileName, FileFormat fileFormat) que permite salvar Word como PDF, XPS, HTML, RTF, etc. Se você deseja apenas salvar seus documentos do Word como PDFs normais sem configurações adicionais, Siga os passos abaixo.

  • Crie um objeto Documento.
  • Carregue um documento do Word de amostra usando o método Document.LoadFromFile().
  • Salve o documento em PDF usando o método Doucment.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Create word document
document = Document()

# Load a doc or docx file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

#Save the document to PDF
document.SaveToFile("output/ToPDF.pdf", FileFormat.PDF)
document.Close()

Python: Convert Word to PDF

Converta Word em PDF protegido por senha em Python

Para converter Word em um PDF protegido por senha, você pode utilizar o método Document.SaveToFile(string fileName, ToPdfParameterList paramList), onde o parâmetro ToPdfParameterList permite controlar o processo de conversão de um documento Word em formato PDF. Isso inclui opções como criptografar o documento durante a conversão. Aqui estão as etapas específicas para realizar esta tarefa.

  • Crie um objeto Documento.
  • Carregue um documento do Word de amostra usando o método Document.LoadFromFile().
  • Crie um objeto ToPdfParameterList, que é usado para definir opções de conversão.
  • Especifique a senha de abertura e a senha de permissão e defina ambas as senhas para o PDF gerado usando o método ToPdfParameterList.PdfSecurity.Encrypt().
  • Salve o documento do Word em PDF com senha usando o método Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parameter = ToPdfParameterList()

# Specify open password and permission password
openPsd = "abc-123"
permissionPsd = "permission"

# Protect the PDF to be generated with open password and permission password
parameter.PdfSecurity.Encrypt(openPsd, permissionPsd, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit)

# Save the Word document to PDF
document.SaveToFile("output/ToPdfWithPassword.pdf", parameter)
document.Close()

Python: Convert Word to PDF

Converta Word em PDF com marcadores em Python

Adicionar marcadores a um documento pode melhorar sua legibilidade. Ao criar PDF a partir do Word, você pode manter os marcadores existentes ou criar novos com base nos títulos. Aqui estão as etapas para converter Word em PDF enquanto mantém os marcadores.

  • Crie um objeto Documento.
  • Carregue um arquivo Word usando o método Document.LoadFromFile().
  • Crie um objeto ToPdfParameterList, que é usado para definir opções de conversão.
  • Crie marcadores em PDF a partir dos títulos no Word definindo ToPdfParameterList.CreateWordBookmarksUsingHeadings como true.
  • Salve o documento em PDF com marcadores usando o método Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parames = ToPdfParameterList()

# Create bookmarks from Word headings
parames.CreateWordBookmarksUsingHeadings = True

# Create bookmarks in PDF from existing bookmarks in Word
# parames.CreateWordBookmarks = True

# Save the document to PDF
document.SaveToFile("output/ToPdfWithBookmarks.pdf", FileFormat.PDF)
document.Close()

Python: Convert Word to PDF

Converta Word em PDF com fontes incorporadas em Python

Para garantir a aparência consistente de um documento PDF em qualquer dispositivo, você provavelmente precisará incorporar fontes no documento PDF gerado. A seguir estão as etapas para incorporar as fontes usadas em um documento do Word no PDF resultante.

  • Crie um objeto Documento.
  • Carregue um arquivo Word de amostra usando o método Document.LoadFromFile().
  • Crie um objeto ToPdfParameterList, que é usado para definir opções de conversão.
  • Incorpore fontes no PDF gerado por meio da propriedade ToPdfParameterList.IsEmbeddedAllFonts.
  • Salve o documento em PDF usando o método Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parameter = ToPdfParameterList()

# Embed fonts in PDF
parameter.IsEmbeddedAllFonts = True

# Save the Word document to PDF
document.SaveToFile("output/EmbedFonts.pdf", parameter)
document.Close()

Python: Convert Word to PDF

Defina a qualidade da imagem ao converter Word em PDF em Python

Ao converter um documento Word para PDF, é importante considerar o tamanho do arquivo resultante, especialmente se ele contiver inúmeras imagens de alta qualidade. Você tem a opção de compactar a qualidade da imagem durante o processo de conversão. Para fazer isso, siga as etapas abaixo.

  • Crie um objeto Documento.
  • Carregue um arquivo Word de amostra usando o método Document.LoadFromFile().
  • Defina a qualidade da imagem através da propriedade Document.JPEGQuality.
  • Salve o documento em PDF usando o método Doucment.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Compress image to 40% of its original quality
document.JPEGQuality = 40

# Preserve original image quality
# document.JPEGQuality = 100

# Save the Word document to PDF
document.SaveToFile("output/SetImageQuality.pdf", FileFormat.PDF)
document.Close()

Solicite uma licença temporária

Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também

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

Установите Spire.Doc for Python

Для этого сценария требуется Spire.Doc for Python и Plum-Dispatch v1.7.4. Их можно легко установить в ваш VS Code с помощью следующей команды pip.

pip install Spire.Doc

Если вы не знаете, как установить, обратитесь к этому руководству: Как установить Spire.Doc for Python в VS Code.

Конвертируйте Doc или Docx в PDF в Python

Spire.Doc for Python предлагает метод Document.SaveToFile(string fileName, FileFormat fileFormat), который позволяет сохранять Word в формате PDF, XPS, HTML, RTF и т. д. Если вы просто хотите сохранить документы Word как обычные PDF-файлы без дополнительных настроек, выполните следующие действия.

  • Создайте объект Документ.
  • Загрузите образец документа Word, используя метод Document.LoadFromFile().
  • Сохраните документ в PDF с помощью метода Doucment.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Create word document
document = Document()

# Load a doc or docx file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

#Save the document to PDF
document.SaveToFile("output/ToPDF.pdf", FileFormat.PDF)
document.Close()

Python: Convert Word to PDF

Преобразование Word в PDF-файл, защищенный паролем, в Python

Чтобы преобразовать Word в PDF-файл, защищенный паролем, вы можете использовать метод Document.SaveToFile(string fileName, ToPdfParameterList paramList), где параметр ToPdfParameterList позволяет вам управлять процессом преобразования документа Word в формат PDF. Сюда входят такие параметры, как шифрование документа во время преобразования. Вот конкретные шаги для выполнения этой задачи.

  • Создайте объект Документ.
  • Загрузите образец документа Word, используя метод Document.LoadFromFile().
  • Создайте объект ToPdfParameterList, который используется для установки параметров преобразования.
  • Укажите открытый пароль и пароль разрешения, а затем установите оба пароля для созданного PDF-файла с помощью метода ToPdfParameterList.PdfSecurity.Encrypt().
  • Сохраните документ Word в PDF с паролем, используя метод Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parameter = ToPdfParameterList()

# Specify open password and permission password
openPsd = "abc-123"
permissionPsd = "permission"

# Protect the PDF to be generated with open password and permission password
parameter.PdfSecurity.Encrypt(openPsd, permissionPsd, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit)

# Save the Word document to PDF
document.SaveToFile("output/ToPdfWithPassword.pdf", parameter)
document.Close()

Python: Convert Word to PDF

Преобразование Word в PDF с закладками в Python

Добавление закладок в документ может улучшить его читабельность. При создании PDF-файла из Word вы можете сохранить существующие закладки или создать новые на основе заголовков. Вот шаги по преобразованию Word в PDF с сохранением закладок.

  • Создайте объект Документ.
  • Загрузите файл Word с помощью метода Document.LoadFromFile().
  • Создайте объект ToPdfParameterList, который используется для установки параметров преобразования.
  • Создайте закладки в PDF-файле из заголовков в Word, установив для ToPdfParameterList.CreateWordBookmarksUsingHeadings значение true.
  • Сохраните документ в PDF с закладками, используя метод Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parames = ToPdfParameterList()

# Create bookmarks from Word headings
parames.CreateWordBookmarksUsingHeadings = True

# Create bookmarks in PDF from existing bookmarks in Word
# parames.CreateWordBookmarks = True

# Save the document to PDF
document.SaveToFile("output/ToPdfWithBookmarks.pdf", FileFormat.PDF)
document.Close()

Python: Convert Word to PDF

Преобразование Word в PDF с помощью шрифтов, встроенных в Python

Чтобы обеспечить единообразный вид PDF-документа на любом устройстве, вам, вероятно, потребуется встроить шрифты в созданный PDF-документ. Ниже приведены шаги по встраиванию шрифтов, используемых в документе Word, в полученный PDF-файл.

  • Создайте объект Документ.
  • Загрузите образец файла Word, используя метод Document.LoadFromFile().
  • Создайте объект ToPdfParameterList, который используется для установки параметров преобразования.
  • Встраивайте шрифты в созданный PDF-файл с помощью свойства ToPdfParameterList.IsEmbeddedAllFonts.
  • Сохраните документ в PDF с помощью метода Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parameter = ToPdfParameterList()

# Embed fonts in PDF
parameter.IsEmbeddedAllFonts = True

# Save the Word document to PDF
document.SaveToFile("output/EmbedFonts.pdf", parameter)
document.Close()

Python: Convert Word to PDF

Установите качество изображения при преобразовании Word в PDF в Python

При преобразовании документа Word в PDF важно учитывать размер полученного файла, особенно если он содержит множество изображений высокого качества. У вас есть возможность сжать качество изображения в процессе преобразования. Для этого выполните следующие действия.

  • Создайте объект Документ.
  • Загрузите образец файла Word, используя метод Document.LoadFromFile().
  • Установите качество изображения через свойство Document.JPEGQuality.
  • Сохраните документ в PDF с помощью метода Doucment.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Compress image to 40% of its original quality
document.JPEGQuality = 40

# Preserve original image quality
# document.JPEGQuality = 100

# Save the Word document to PDF
document.SaveToFile("output/SetImageQuality.pdf", FileFormat.PDF)
document.Close()

Подать заявку на временную лицензию

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

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

Monday, 18 December 2023 02:30

Python: Word in PDF konvertieren

Heutzutage spielen digitale Dokumente eine bedeutende Rolle in unserem täglichen Leben, sowohl im privaten als auch im beruflichen Umfeld. Ein solches gängiges Format ist Microsoft Word, das zum Erstellen und Bearbeiten von Textdokumenten verwendet wird. Es kann jedoch vorkommen, dass Sie Ihre Word-Dateien in ein allgemein zugängliches Format wie PDF konvertieren müssen. PDFs bieten Vorteile wie die Beibehaltung der Formatierung, die Sicherstellung der Kompatibilität und die Wahrung der Dokumentintegrität auf verschiedenen Geräten und Betriebssystemen. In diesem Artikel erfahren Sie, wie das geht Konvertieren Sie Word in Python in PDF Verwendung von Spire.Doc for Python.

Installieren Sie Spire.Doc for Python

Dieses Szenario erfordert Spire.Doc for Python und plum-dispatch v1.7.4. Sie können mit dem folgenden pip-Befehl einfach in Ihrem VS-Code installiert werden.

pip install Spire.Doc

Wenn Sie sich bei der Installation nicht sicher sind, lesen Sie bitte dieses Tutorial: So installieren Sie Spire.Doc for Python in VS Code

Konvertieren Sie Doc oder Docx in Python in PDF

Spire.Doc for Python bietet die Methode Document.SaveToFile(string fileName, FileFormat fileFormat), mit der Word als PDF, XPS, HTML, RTF usw. gespeichert werden kann. Wenn Sie Ihre Word-Dokumente nur als normale PDFs ohne zusätzliche Einstellungen speichern möchten, folgen Sie den unteren Schritten.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Beispiel-Word-Dokument mit der Methode Document.LoadFromFile().
  • Speichern Sie das Dokument mit der Methode Doucment.SaveToFile() im PDF-Format.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create word document
document = Document()

# Load a doc or docx file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

#Save the document to PDF
document.SaveToFile("output/ToPDF.pdf", FileFormat.PDF)
document.Close()

Python: Convert Word to PDF

Konvertieren Sie Word in Python in ein passwortgeschütztes PDF

Um Word in eine passwortgeschützte PDF-Datei zu konvertieren, können Sie die Methode Document.SaveToFile(string fileName, ToPdfParameterList paramList) verwenden, wobei der Parameter ToPdfParameterList es Ihnen ermöglicht, den Konvertierungsprozess eines Word-Dokuments in ein PDF-Format zu steuern. Dazu gehören Optionen wie die Verschlüsselung des Dokuments während der Konvertierung. Hier sind die spezifischen Schritte, um diese Aufgabe zu erfüllen.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Beispiel-Word-Dokument mit der Methode Document.LoadFromFile().
  • Erstellen Sie ein ToPdfParameterList-Objekt, das zum Festlegen von Konvertierungsoptionen verwendet wird.
  • Geben Sie das Öffnungskennwort und das Berechtigungskennwort an und legen Sie dann beide Kennwörter für die generierte PDF-Datei mithilfe der Methode ToPdfParameterList.PdfSecurity.Encrypt() fest.
  • Speichern Sie das Word-Dokument mit der Methode Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) als PDF mit Passwort.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parameter = ToPdfParameterList()

# Specify open password and permission password
openPsd = "abc-123"
permissionPsd = "permission"

# Protect the PDF to be generated with open password and permission password
parameter.PdfSecurity.Encrypt(openPsd, permissionPsd, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit)

# Save the Word document to PDF
document.SaveToFile("output/ToPdfWithPassword.pdf", parameter)
document.Close()

Python: Convert Word to PDF

Konvertieren Sie Word mit Lesezeichen in Python in PDF

Durch das Hinzufügen von Lesezeichen zu einem Dokument kann dessen Lesbarkeit verbessert werden. Wenn Sie PDF-Dateien aus Word erstellen, möchten Sie möglicherweise die vorhandenen Lesezeichen beibehalten oder basierend auf den Überschriften neue erstellen. Hier sind die Schritte zum Konvertieren von Word in PDF unter Beibehaltung der Lesezeichen.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie eine Word-Datei mit der Methode Document.LoadFromFile().
  • Erstellen Sie ein ToPdfParameterList-Objekt, das zum Festlegen von Konvertierungsoptionen verwendet wird.
  • Erstellen Sie Lesezeichen in PDF aus den Überschriften in Word, indem Sie ToPdfParameterList.CreateWordBookmarksUsingHeadings auf true setzen.
  • Speichern Sie das Dokument mit der Methode Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) als PDF mit Lesezeichen.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parames = ToPdfParameterList()

# Create bookmarks from Word headings
parames.CreateWordBookmarksUsingHeadings = True

# Create bookmarks in PDF from existing bookmarks in Word
# parames.CreateWordBookmarks = True

# Save the document to PDF
document.SaveToFile("output/ToPdfWithBookmarks.pdf", FileFormat.PDF)
document.Close()

Python: Convert Word to PDF

Konvertieren Sie Word mit in Python eingebetteten Schriftarten in PDF

Um ein einheitliches Erscheinungsbild eines PDF-Dokuments auf jedem Gerät sicherzustellen, müssen Sie wahrscheinlich Schriftarten in das generierte PDF-Dokument einbetten. Im Folgenden finden Sie die Schritte zum Einbetten der in einem Word-Dokument verwendeten Schriftarten in die resultierende PDF-Datei.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie eine Beispiel-Word-Datei mit der Methode Document.LoadFromFile().
  • Erstellen Sie ein ToPdfParameterList-Objekt, das zum Festlegen von Konvertierungsoptionen verwendet wird.
  • Betten Sie Schriftarten über die Eigenschaft ToPdfParameterList.IsEmbeddedAllFonts in generierte PDFs ein.
  • Speichern Sie das Dokument mit der Methode Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) als PDF.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Create a ToPdfParameterList object
parameter = ToPdfParameterList()

# Embed fonts in PDF
parameter.IsEmbeddedAllFonts = True

# Save the Word document to PDF
document.SaveToFile("output/EmbedFonts.pdf", parameter)
document.Close()

Python: Convert Word to PDF

Legen Sie die Bildqualität beim Konvertieren von Word in PDF in Python fest

Beim Konvertieren eines Word-Dokuments in PDF ist es wichtig, die Größe der resultierenden Datei zu berücksichtigen, insbesondere wenn diese zahlreiche hochwertige Bilder enthält. Sie haben die Möglichkeit, die Bildqualität während des Konvertierungsvorgangs zu komprimieren. Befolgen Sie dazu die folgenden Schritte.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie eine Beispiel-Word-Datei mit der Methode Document.LoadFromFile().
  • Legen Sie die Bildqualität über die Eigenschaft Document.JPEGQuality fest.
  • Speichern Sie das Dokument mit der Methode Doucment.SaveToFile() im PDF-Format.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")

# Compress image to 40% of its original quality
document.JPEGQuality = 40

# Preserve original image quality
# document.JPEGQuality = 100

# Save the Word document to PDF
document.SaveToFile("output/SetImageQuality.pdf", FileFormat.PDF)
document.Close()

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch