Python save excel to pdf

Saving an Excel sheet to Pdf with Python

Saving a finished report or table in Excel is easy. You choose SaveAs and save the sheet as Pdf. Doing this automatically with Python is a bit trickier though. In this post, we will take a closer look on how to do this with the win32 library. The full code is available at the bottom of the post. Note that you need Excel installed in order to run this script successfully.

Installing dependencies

install the win32 library first with: pip install pypiwin32 . This will install the Win32 Api library, which according to PyPi contains: Python extensions for Microsoft Windows Provides access to much of the Win32 API, the ability to create and use COM objects, and the Pythonwin environment.

File paths

To get the file paths we use pathlib. Pathlib was introduced in Python 3.4 so it is quite new (Using Python 3.8 during the writing of this article). We specify the name of the Excel workbook we want to make a pdf of, and also the output pdf’s name.

Читайте также:  Добро пожаловать, JSP!

excel_file = «pdf_me.xlsx»
pdf_file = «pdf_me.pdf»

We then create paths from our current working directory (cwd) with Pathlibs cwd() method.

excel_path = str(pathlib.Path.cwd() / excel_file)
pdf_path = str(pathlib.Path.cwd() / pdf_file)

Firing up Excel

Excel is next up. We start the Excel application and hide it.

excel = client.DispatchEx(«Excel.Application»)
excel.Visible = 0

We then open our workbook wb = excel.Workbooks.Open(excel_path) and load our first sheet with ws = wb.Worksheets[1]

Now it is time to use the SaveAs to save our sheet as a pdf. wb.SaveAs(pdf_path, FileFormat=57) Fileformat 57 is the pdf file format.

We then close our workbook and quit our Excel application. Our pdf is now saved in our working directory.

The code

from win32com import client import win32api import pathlib ### pip install pypiwin32 if module not found excel_file = "pdf_me.xlsx" pdf_file = "pdf_me.pdf" excel_path = str(pathlib.Path.cwd() / excel_file) pdf_path = str(pathlib.Path.cwd() / pdf_file) excel = client.DispatchEx("Excel.Application") excel.Visible = 0 wb = excel.Workbooks.Open(excel_path) ws = wb.Worksheets[1] try: wb.SaveAs(pdf_path, FileFormat=57) except Exception as e: print("Failed to convert") print(str(e)) finally: wb.Close() excel.Quit()

Источник

How to Convert Excel to PDF Using Python

Vyom Srivastava

Illustration: How to Convert Excel to PDF Using Python

In this post, you’ll learn how to convert Excel files to PDFs in your Python application using PSPDFKit’s XLSX to PDF Python API. With our API, you can convert up to 100 PDF files per month for free. All you need to do is create a free account to get access to your API key.

PSPDFKit API

Document conversion is just one of our 30+ PDF API tools. You can combine our conversion tool with other tools to create complex document processing workflows. You’ll be able to convert various file formats into PDFs and then:

  • Merge several resulting PDFs into one
  • OCR, watermark, or flatten PDFs
  • Remove or duplicate specific PDF pages

Once you create your account, you’ll be able to access all our PDF API tools.

Step 1 — Creating a Free Account on PSPDFKit

Go to our website, where you’ll see the page below, prompting you to create your free account.

Free account PSPDFKit API

Once you’ve created your account, you’ll be welcomed by the page below, which shows an overview of your plan details.

Free plan PSPDFKit API

As you can see in the bottom-left corner, you’ll start with 100 documents to process, and you’ll be able to access all our PDF API tools.

Step 2 — Obtaining the API Key

After you’ve verified your email, you can get your API key from the dashboard. In the menu on the left, click API Keys. You’ll see the following page, which is an overview of your keys:

Convert Excel to PDF Python API Key

Copy the Live API Key, because you’ll need this for the Excel to PDF API.

Step 3 — Setting Up Folders and Files

Now, create a folder called excel_to_pdf and open it in a code editor. For this tutorial, you’ll use VS Code as your primary code editor. Next, create two folders inside excel_to_pdf and name them input_documents and processed_documents .

Now, copy your Excel file to the input_documents folder and rename it to document.xlsx . You can use our demo document as an example.

Then, in the root folder, excel_to_pdf , create a file called processor.py . This is the file where you’ll keep your code.

Your folder structure will look like this:

excel_to_pdf ├── input_documents | └── document.xlsx ├── processed_documents └── processor.py

Step 4 — Writing the Code

Open the processor.py file and paste the code below into it:

import requests import json instructions = < 'parts': [ < 'file': 'document' > ] > response = requests.request( 'POST', 'https://api.pspdfkit.com/build', headers = < 'Authorization': 'Bearer YOUR API KEY HERE' >, files = < 'document': open('input_documents/document.xlsx', 'rb') >, data = < 'instructions': json.dumps(instructions) >, stream = True ) if response.ok: with open('processed_documents/result.pdf', 'wb') as fd: for chunk in response.iter_content(chunk_size=8096): fd.write(chunk) else: print(response.text) exit()

ℹ️ Note: Make sure to replace YOUR_API_KEY_HERE with your API key.

Code Explanation

In the code above, you first import the requests and json dependencies. After that, you create the instructions for the API call.

You then use the requests module to make the API call, and once it succeeds, you store the result in the processed_documents folder.

Output

To execute the code, use the command below:

Once the code has been executed, you’ll see a new processed file under the processed_documents folder called result.pdf .

The folder structure will look like this:

excel_to_pdf ├── input_documents | └── document.xlsx ├── processed_documents | └── result.pdf └── processor.py

Final Words

In this post, you learned how to easily and seamlessly convert Excel files to PDF documents for your Python application using our Excel to PDF Python API.

You can integrate these functions into your existing applications. With the same API token, you can also perform other operations, such as merging several documents into a single PDF, adding watermarks, and more. To get started with a free trial, sign up here.

Источник

How to convert Excel file to PDF with Python

Describes how to convert an Excel sheet to PDF using Python.
There seem to be many libraries for manipulating Excel files in Python, but this time I will use a module called win32com.

win32com can handle Windows COM objects. Just like using COM objects in Excel VBA.

Environment

Install

win32com is not included by default, so install it.

Now you can do import win32com .

Convert Excel file to PDF

I prepared the pre-conversion Excel file (I just brought an Excel template).
One sheet is a calendar for one month, and there are 12 sheets (one year).
Convert this to a single PDF file.

Excel file

To convert an Excel file to PDF, simply operate Excel from win32com, open the file and save it as PDF.

The following is a sample program.

     All 12 sheets are specified and exported to a PDF file.

The output PDF is as follows.

Output PDF file

I was able to create PDF more easily than I expected.
It is interesting that there are many other possibilities.

Reference

[Python] Replace text in Excel cells

[Python] Replace text in Excel cells

Replace strings in Excel cells with Python. It can be used …

How to open Excel file with password in PowerShell

Open an Excel workbook with password in PowerShell. When …

Replace string in Excel with PowerShell

Replace string in Excel with PowerShell

Replace strings in cells in Excel using PowerShell. Imagine …

Make Python & Selenium program executable (.exe) (How to include webdriver in .exe)

Make a program created with Python & Selenium into an …

[PyInstaller]Make Python an executable file

PyInstaller can be used to convert a program created with …

[PyInstaller] Create multiple exe’s in one folder

PyInstaller makes it easy to create an exe, but I …

Hide the console in Python Selenium

Running Python Selenium causes the ChromeDriver console …

Источник

Python: Convert Excel to PDF

Converting Excel files to PDF format can be a useful way to share and distribute spreadsheets, especially if you want to ensure that the formatting and layout of the file remains consistent across different devices and software. In addition, PDFs often appear more polished and professional than Excel files, making them a popular choice for official reports, presentations, and other business documents. In this article, you will learn how to convert Excel to PDF in Python using Spire.XLS for Python.

Install Spire.XLS for Python

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

pip install Spire.XLS-for-Python pip install plum-dispatch==1.7.4

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

Convert a Whole Excel Document to PDF in Python

The Workbook.SaveToFile() method is used to convert a complete Excel document into a single PDF file. Once the conversion is done, each worksheet will appear as a separate page in the resultant PDF file. To control the conversion settings, use the Workbook.ConverterSetting property.

The following are the detailed steps to convert an Excel document to a PDF file in Python.

  • Create a Workbook object.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Set the margins of every worksheet through Worksheet.PageSetup property, which will later become the blank edges of the generated PDF.
  • Set the Excel to PDF conversion options through the properties under Workbook.ConverterSetting object.
  • Convert the whole Excel document to PDF using Workbook.SaveToFile() method.
from spire.xls import * from spire.common import * # Create a Workbook object workbook = Workbook() # Load an Excel document workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.xlsx") # Iterate through the worksheets in the workbook for sheet in workbook.Worksheets: # Get the PageSetup object pageSetup = sheet.PageSetup; # Set page margins pageSetup.TopMargin = 0.3; pageSetup.BottomMargin = 0.3; pageSetup.LeftMargin = 0.3; pageSetup.RightMargin = 0.3; # Set worksheet to fit to page when converting workbook.ConverterSetting.SheetFitToPage = True # Convert to PDF file workbook.SaveToFile("output/ToPdf.pdf", FileFormat.PDF) workbook.Dispose()

Python: Convert Excel to PDF

Convert a Particular Worksheet to PDF in Python

The Worksheet.SaveToPdf() method is used to convert a specific worksheet into a PDF document. The detailed steps are as follows.

  • Create a Workbook object.
  • Load an Excel document using Workbook.LoadFromFile() method.
  • Get a particular worksheet through Workbook.Worksheets[] property.
  • Set the margins of the worksheet through Worksheet.PageSetup property, which will later become the blank edges of the generated PDF.
  • Set the Excel to PDF conversion options through the properties under Workbook.ConverterSetting object.
  • Convert the worksheet to PDF using Worksheet.SaveToPdf() method.
from spire.xls import * from spire.common import * # Create a Workbook object workbook = Workbook() # Load an Excel document workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.xlsx") # Get a particular worksheet sheet = workbook.Worksheets[1]; # Get the PageSetup object pageSetup = sheet.PageSetup; # Set page margins pageSetup.TopMargin = 0.3; pageSetup.BottomMargin = 0.3; pageSetup.LeftMargin = 0.3; pageSetup.RightMargin = 0.3; # Set worksheet to fit to page when converting workbook.ConverterSetting.SheetFitToPage = True # Convert the worksheet to PDF file sheet.SaveToPdf("output/WorksheetToPdf.pdf") workbook.Dispose()

Python: Convert Excel to PDF

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.

Источник

Оцените статью