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

Monday, 18 December 2023 02:29

Python: convertir Word a PDF

Hoy en día, los documentos digitales juegan un papel importante en nuestra vida diaria, tanto en el ámbito personal como profesional. Uno de esos formatos comunes es Microsoft Word, que se utiliza para crear y editar documentos de texto. Sin embargo, puede llegar un momento en el que necesites convertir tus archivos de Word a un formato más accesible universalmente, como PDF. Los archivos PDF ofrecen ventajas como preservar el formato, garantizar la compatibilidad y mantener la integridad del documento en diferentes dispositivos y sistemas operativos. En este artículo, aprenderá cómo convertir Word a PDF en Python 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 el siguiente comando 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 Doc o Docx a PDF en Python

Spire.Doc for Python ofrece el método Document.SaveToFile(string fileName, FileFormat fileFormat) que permite guardar Word como PDF, XPS, HTML, RTF, etc. Si solo desea guardar sus documentos de Word como PDF normales sin configuraciones adicionales, siga los pasos a continuación.

  • Crea un objeto de documento.
  • Cargue un documento de Word de muestra utilizando el método Document.LoadFromFile().
  • Guarde el documento en PDF utilizando el 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

Convierta Word a PDF protegido con contraseña en Python

Para convertir Word a un PDF protegido con contraseña, puede utilizar el método Document.SaveToFile(string fileName, ToPdfParameterList paramList), donde el parámetro ToPdfParameterList le permite controlar el proceso de conversión de un documento de Word a un formato PDF. Esto incluye opciones como cifrar el documento durante la conversión. Estos son los pasos específicos para realizar esta tarea.

  • Crea un objeto de documento.
  • Cargue un documento de Word de muestra utilizando el método Document.LoadFromFile().
  • Cree un objeto ToPdfParameterList, que se utiliza para configurar las opciones de conversión.
  • Especifique la contraseña de apertura y la contraseña de permiso y luego configure ambas contraseñas para el PDF generado utilizando el método ToPdfParameterList.PdfSecurity.Encrypt().
  • Guarde el documento de Word en PDF con contraseña utilizando el 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

Convierta Word a PDF con marcadores en Python

Agregar marcadores a un documento puede mejorar su legibilidad. Al crear un PDF desde Word, es posible que desee conservar los marcadores existentes o crear otros nuevos basados en los títulos. Estos son los pasos para convertir Word a PDF manteniendo los marcadores.

  • Crea un objeto de documento.
  • Cargue un archivo de Word usando el método Document.LoadFromFile().
  • Cree un objeto ToPdfParameterList, que se utiliza para configurar las opciones de conversión.
  • Cree marcadores en PDF a partir de los encabezados en Word configurando ToPdfParameterList.CreateWordBookmarksUsingHeadings en verdadero.
  • Guarde el documento en PDF con marcadores utilizando el 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

Convierta Word a PDF con fuentes integradas en Python

Para garantizar una apariencia uniforme de un documento PDF en cualquier dispositivo, probablemente necesite incrustar fuentes en el documento PDF generado. Los siguientes son los pasos para incrustar las fuentes utilizadas en un documento de Word en el PDF resultante.

  • Crea un objeto de documento.
  • Cargue un archivo de Word de muestra utilizando el método Document.LoadFromFile().
  • Cree un objeto ToPdfParameterList, que se utiliza para configurar las opciones de conversión.
  • Incruste fuentes en el PDF generado a través de la propiedad ToPdfParameterList.IsEmbeddedAllFonts.
  • Guarde el documento en PDF utilizando el 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

Establecer la calidad de la imagen al convertir Word a PDF en Python

Al convertir un documento de Word a PDF, es importante considerar el tamaño del archivo resultante, especialmente si contiene numerosas imágenes de alta calidad. Tiene la opción de comprimir la calidad de la imagen durante el proceso de conversión. Para hacer esto, siga los pasos a continuación.

  • Crea un objeto de documento.
  • Cargue un archivo de Word de muestra utilizando el método Document.LoadFromFile().
  • Establezca la calidad de la imagen a través de la propiedad Document.JPEGQuality.
  • Guarde el documento en PDF utilizando el 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()

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

Monday, 18 December 2023 02:27

Python: Word를 PDF로 변환

오늘날 디지털 문서는 개인적 환경과 직업적 환경 모두에서 일상 생활에서 중요한 역할을 합니다. 이러한 일반적인 형식 중 하나는 텍스트 문서를 작성하고 편집하는 데 사용되는 Microsoft Word입니다. 그러나 Word 파일을 PDF와 같이 보다 보편적으로 액세스할 수 있는 형식으로 변환해야 할 때가 있을 수 있습니다. PDF는 서식 유지, 호환성 보장, 다양한 장치 및 운영 체제 전반에서 문서 무결성 유지와 같은 이점을 제공합니다. 이 기사에서는 다음 방법을 배웁니다 Python에서 Word를 PDF로 변환 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에서 Doc 또는 Docx를 PDF로 변환

Spire.Doc for Python Word를 PDF, XPS, HTML, RTF 등으로 저장할 수 있는 Document.SaveToFile(string fileName, FileFormat fileFormat) 메서드를 제공합니다. 추가 설정 없이 Word 문서를 일반 PDF로 저장하고 싶다면, 아래 단계를 따르십시오.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 샘플 Word 문서를 로드합니다.
  • Doucment.SaveToFile() 메서드를 사용하여 문서를 PDF로 저장합니다.
  • 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

Python에서 Word를 비밀번호로 보호된 PDF로 변환

Word를 암호로 보호된 PDF로 변환하려면 Document.SaveToFile(string fileName, ToPdfParameterList paramList) 메서드를 활용할 수 있습니다. 여기서 ToPdfParameterList 매개 변수를 사용하면 Word 문서를 PDF 형식으로 변환하는 과정을 제어할 수 있습니다. 여기에는 변환 중 문서 암호화와 같은 옵션이 포함됩니다. 이 작업을 수행하기 위한 구체적인 단계는 다음과 같습니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 샘플 Word 문서를 로드합니다.
  • 변환 옵션을 설정하는 데 사용되는 ToPdfParameterList 개체를 만듭니다.
  • 열기 암호와 권한 암호를 지정한 다음 ToPdfParameterList.PdfSecurity.Encrypt() 메서드를 사용하여 생성된 PDF에 대해 두 암호를 모두 설정합니다.
  • Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) 메서드를 사용하여 Word 문서를 비밀번호로 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()

# 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

Python의 책갈피를 사용하여 Word를 PDF로 변환

문서에 책갈피를 추가하면 가독성이 향상될 수 있습니다. Word에서 PDF를 만들 때 기존 책갈피를 유지하거나 제목을 기반으로 새 책갈피를 만들고 싶을 수 있습니다. 책갈피를 유지하면서 Word를 PDF로 변환하는 단계는 다음과 같습니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 파일을 로드합니다.
  • 변환 옵션을 설정하는 데 사용되는 ToPdfParameterList 개체를 만듭니다.
  • ToPdfParameterList.CreateWordBookmarksUsingHeadings를 true로 설정하여 Word의 제목에서 PDF의 책갈피를 만듭니다.
  • Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) 메서드를 사용하여 책갈피를 사용하여 문서를 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
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

Python에 포함된 글꼴을 사용하여 Word를 PDF로 변환

모든 장치에서 PDF 문서의 일관된 모양을 보장하려면 생성된 PDF 문서에 글꼴을 포함해야 할 수도 있습니다. 다음은 Word 문서에 사용된 글꼴을 결과 PDF에 포함시키는 단계입니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 샘플 Word 파일을 로드합니다.
  • 변환 옵션을 설정하는 데 사용되는 ToPdfParameterList 개체를 만듭니다.
  • ToPdfParameterList.IsEmbeddedAllFonts 속성을 통해 생성된 PDF에 글꼴을 포함합니다.
  • Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) 메서드를 사용하여 문서를 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

Python에서 Word를 PDF로 변환할 때 이미지 품질 설정

Word 문서를 PDF로 변환할 때, 특히 고품질 이미지가 많이 포함된 경우 결과 파일의 크기를 고려하는 것이 중요합니다. 변환 프로세스 중에 이미지 품질을 압축할 수 있는 옵션이 있습니다. 이렇게 하려면 아래 단계를 따르세요.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 샘플 Word 파일을 로드합니다.
  • Document.JPEGQuality 속성을 통해 이미지 품질을 설정합니다.
  • Doucment.SaveToFile() 메서드를 사용하여 문서를 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")

# 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:26

Python: converti Word in PDF

Al giorno d'oggi, i documenti digitali svolgono un ruolo significativo nella nostra vita quotidiana, sia in ambito personale che professionale. Uno di questi formati comuni è Microsoft Word, utilizzato per creare e modificare documenti di testo. Tuttavia, potrebbe arrivare il momento in cui sarà necessario convertire i file Word in un formato più universalmente accessibile, come PDF. I PDF offrono vantaggi come preservare la formattazione, garantire la compatibilità e mantenere l'integrità del documento su diversi dispositivi e sistemi operativi. In questo articolo imparerai come farlo convertire Word in PDF in Python 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 il seguente comando 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 Doc o Docx in PDF in Python

Spire.Doc for Python offre il metodo Document.SaveToFile(string fileName, FileFormat fileFormat) che consente di salvare Word come PDF, XPS, HTML, RTF, ecc. Se desideri semplicemente salvare i tuoi documenti Word come normali PDF senza impostazioni aggiuntive, seguire i passaggi seguenti.

  • Creare un oggetto Documento.
  • Carica un documento Word di esempio utilizzando il metodo Document.LoadFromFile().
  • Salva il documento in PDF utilizzando il metodo 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

Converti Word in PDF protetto da password in Python

Per convertire Word in un PDF protetto da password, è possibile utilizzare il metodo Document.SaveToFile(string fileName, ToPdfParameterList paramList), dove il parametro ToPdfParameterList consente di controllare il processo di conversione di un documento Word in un formato PDF. Ciò include opzioni come la crittografia del documento durante la conversione. Ecco i passaggi specifici per eseguire questa attività.

  • Creare un oggetto Documento.
  • Carica un documento Word di esempio utilizzando il metodo Document.LoadFromFile().
  • Creare un oggetto ToPdfParameterList, utilizzato per impostare le opzioni di conversione.
  • Specificare la password di apertura e la password di autorizzazione, quindi impostare entrambe le password per il PDF generato utilizzando il metodo ToPdfParameterList.PdfSecurity.Encrypt().
  • Salva il documento Word in PDF con password utilizzando il metodo 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

Converti Word in PDF con i segnalibri in Python

L'aggiunta di segnalibri a un documento può migliorarne la leggibilità. Quando crei un PDF da Word, potresti voler mantenere i segnalibri esistenti o crearne di nuovi in base ai titoli. Ecco i passaggi per convertire Word in PDF mantenendo i segnalibri.

  • Creare un oggetto Documento.
  • Carica un file Word utilizzando il metodo Document.LoadFromFile().
  • Creare un oggetto ToPdfParameterList, utilizzato per impostare le opzioni di conversione.
  • Crea segnalibri in PDF dalle intestazioni in Word impostando ToPdfParameterList.CreateWordBookmarksUsingHeadings su true.
  • Salvare il documento in PDF con i segnalibri utilizzando il metodo 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

Converti Word in PDF con caratteri incorporati in Python

Per garantire un aspetto coerente di un documento PDF su qualsiasi dispositivo, probabilmente dovrai incorporare i caratteri nel documento PDF generato. Di seguito sono riportati i passaggi per incorporare i caratteri utilizzati in un documento Word nel PDF risultante.

  • Creare un oggetto Documento.
  • Carica un file Word di esempio utilizzando il metodo Document.LoadFromFile().
  • Creare un oggetto ToPdfParameterList, utilizzato per impostare le opzioni di conversione.
  • Incorpora i caratteri nel PDF generato tramite la proprietà ToPdfParameterList.IsEmbeddedAllFonts.
  • Salvare il documento in PDF utilizzando il metodo 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

Imposta la qualità dell'immagine durante la conversione di Word in PDF in Python

Quando si converte un documento Word in PDF, è importante considerare la dimensione del file risultante, soprattutto se contiene numerose immagini di alta qualità. Hai la possibilità di comprimere la qualità dell'immagine durante il processo di conversione. Per fare ciò, seguire i passaggi seguenti.

  • Creare un oggetto Documento.
  • Carica un file Word di esempio utilizzando il metodo Document.LoadFromFile().
  • Imposta la qualità dell'immagine tramite la proprietà Document.JPEGQuality.
  • Salva il documento in PDF utilizzando il metodo 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()

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

Page 8 of 66