Excel to pdf script

In this post, you’ll learn how to convert Excel files to PDFs in your JavaScript application using PSPDFKit’s XLSX to PDF JavaScript 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 JavaScript 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.

Next, 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.js. 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.js

Step 4 — Installing Dependencies

To get started converting PDF pages, you first need to install the following dependencies:

  • axios — This package is used for making REST API calls.

  • Form-Data — This package is used for creating form data.

Use the command below to install both of them:

npm install axios
npm install form-data

Step 5 — Writing the Code

Now, open the processor.js file and paste the code below into it:

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

const formData = new FormData();
formData.append(
	'instructions',
	JSON.stringify({
		parts: [
			{
				file: 'document',
			},
		],
	}),
);
formData.append(
	'document',
	fs.createReadStream('input_documents/document.xlsx'),
)(async () => {
	try {
		const response = await axios.post(
			'https://api.pspdfkit.com/build',
			formData,
			{
				headers: formData.getHeaders({
					Authorization: 'Bearer YOUR API KEY HERE',
				}),
				responseType: 'stream',
			},
		);

		response.data.pipe(
			fs.createWriteStream('processed_documents/result.pdf'),
		);
	} catch (e) {
		const errorString = await streamToString(e.response.data);
		console.log(errorString);
	}
})();

function streamToString(stream) {
	const chunks = [];
	return new Promise((resolve, reject) => {
		stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
		stream.on('error', (err) => reject(err));
		stream.on('end', () =>
			resolve(Buffer.concat(chunks).toString('utf8')),
		);
	});
}

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

Code Explanation

Here, you have a form variable that contains the instructions for the API. You’re using createReadStream to read the input PDF file. You then have a function, axios.post(), that’ll make the POST request to the Excel to PDF API.

The response of the API is stored in the processed_documents folder.

Output

To execute the code, use the following command:

On the successful execution of the code, you’ll see a new processed file named result.pdf in the processed_documents folder.

The folder structure will look like this:

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

Final Words

In this post, you learned how to easily and seamlessly convert Excel files to PDF documents for your JavaScript application using our Excel to PDF JavaScript 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.

Permalink

Cannot retrieve contributors at this time


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

import openpyxl
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.pdfbase.ttfonts import TTFont
import os
from pyPDF2 import PdfFileReader, PdfFileMerger
pdfmetrics.registerFont(TTFont(‘Arial’,‘Arial.ttf’))
wb = openpyxl.load_workbook(‘F:\Python\py to pdf\Data.xlsx’)
sheet = wb.get_sheet_by_name(«Sheet1»)
#print(sheet.cell(2,2).value)
page_width = 2156
page_height = 3050
start = 200
start_2 = 700
spread = 80
categories = [«Roll Number: «,«Name: «,«Gender: «,«Age: «,«Board: «,«City: «,«Email: «]
university = «NED University Of Engineering And Technology»
def create_data():
for i in range (2,14):
std_id = sheet.cell(row=i,column=1).value
std_name = sheet.cell(row=i,column=2).value
std_gender = sheet.cell(row=i,column=3).value
std_age = sheet.cell(row=i,column=4).value
std_board = sheet.cell(row=i,column=5).value
std_city = sheet.cell(row=i,column=6).value
std_email = sheet.cell(row=i,column=8).value
data=[std_id,std_name,std_gender,std_age,std_board,std_city,std_email]
c=canvas.Canvas(str(std_name)+‘.pdf’)
c.setPageSize((page_width,page_height))
c.setFont(‘Arial’,80)
text_width = stringWidth(university,‘Arial’,80)
c.drawString((page_widthtext_width)/2,2900,university)
y=2500
for x in range(0,7):
c.setFont(‘Arial’,40)
c.drawString(start,y,categories[x])
c.drawString(start_2,y,str(data[x]))
y-=spread
c.save()
def merge_data():
files_dir = ‘F:\Python\py to pdf’
pdf_files = [f for f in os.listdir(files_dir) if f.endswith(‘.pdf’)]
merger = PdfFileMerger()
for filename in pdf_files:
merger.append(PdfFileReader(os.path.join(files_dir,filename,‘rb’)))
merger.write(os.path.join(files_dir,‘merged_data.pdf’))
create_data()
merge_data()

Содержание

  1. Сохранение документов Excel в PDF на сервере
  2. How to Convert Excel to PDF Using JavaScript
  3. PSPDFKit API
  4. Step 1 — Creating a Free Account on PSPDFKit
  5. Step 2 — Obtaining the API Key
  6. Step 3 — Setting Up Folders and Files
  7. Step 4 — Installing Dependencies
  8. Step 5 — Writing the Code
  9. Code Explanation
  10. Output
  11. Final Words
  12. VBA Excel. Сохранение книг и листов в PDF
  13. Метод ExportAsFixedFormat
  14. Синтаксис
  15. Параметры
  16. Примеры экспорта в PDF
  17. Сохранение в PDF книги Excel
  18. Экспорт всей книги
  19. Экспорт части книги
  20. Convert Excel to PDF Using Python
  21. What is win32com?
  22. How to save Excel as PDF with VBA (10 examples)
  23. Saving Excel workbooks, sheets, charts, and ranges as PDF
  24. Save active sheet as PDF
  25. Save active workbook as PDF
  26. Save selection as PDF
  27. Save a range as PDF
  28. Save a chart as PDF
  29. Adapting the code to your scenario
  30. Notes for saving PDF documents
  31. Selecting specific worksheets before saving as PDF
  32. Looping and saving as separate PDFs
  33. Loop through sheets
  34. Loop through selected sheets
  35. Loop through charts
  36. Other PDF print options
  37. VBA Save to PDF Example using all the options
  38. Other fixed formats available (xlTypeXPS)
  39. Conclusion

Сохранение документов Excel в PDF на сервере

Не так давно появилась задача создать простой сервис по созданию PDF отчетов на основе офисных документов для интранета. И вроде бы все просто, но вот с сохранением Excel в PDF возникли проблемы. Интересно? Прошу под кат.

Как я и сказал, поначалу все казалось легко, у меня были собственные наработки, на хабре была статья. Но обо всем по порядку.

Мои наработки использовали сom объекты excel.application и метод saveAs, это прекрасно работало, пока требовалось взять обычный, красивый документ и сделать из него pdf, но в данном случае файлы были нет так просты.

Во-первых, документы предполагаются трех форматов — xls, xlsx и xml. Во вторых все документы содержат макросы, а некоторые ссылки на другие документы. В третьих они содержат кучу листов, и перекрестные ссылки между листами. Не нужные для отчета листы делаются скрытыми, а на самих листах в каше вспомогательных цифр отчетная информация выделялась областью печати. Нужно ли говорить, что saveAs игнорирует все это богатство и на выходе после танца с бубнами получаем абсолютно не читаемую картину.

Здесь я думаю необходимо сделать лирическое отступление и пояснить, почему с файлами творится такая неразбериха. Я работаю в очень крупной организации, бок обок с кучей бабушке пенсионного возраста. Они не могут даже сделать текст в ячейке жирным, но прекрасно могут говорить начальству о том, что они не «программисты» и не должны это уметь. Начальства у нас тоже много, и в силу жалости к бабушкам или своей компьютерной безграмотности, а быть может, по велению звезд жалобы бабушек поощряются, и все попытки разгрести бардак в документах пресекается.

Вернемся к нашим баранам. В выше упомянутой статье был предложен вариант конвертации «Как вижу» с использованием open office, этот вариант меня не устроил в силу ветреного отношения OO к MS. Некоторые документы действительно открывались в нем корректно, но чаще всего содержимое ехало еще до конвертации.

Был еще третий вариант. Печатать документы на виртуальный принтер, но я решил, что этот вариант я приберегу на самый крайний случай, так это костыль.

И тогда я обратился к гуглу и он дал мне эту замечательную ссылку. Описанный в ней метод ExportAsFixedFormat был тем, что нужно! Но меня опять постигла не удача.

Он начисто игнорировал области печати, а без них получалась каша. Я гуглил, оставлял вопросы на множестве форумах, в том числе и на англоязычных. Ответа не было. Я даже перенес код статьи в C#, но результат не изменился.

После недели изысканий, я решил плюнуть на все и использовать тот самый крайний вариант с виртуальным принтером, но каково же было мое изумление, когда и он проигнорировал область печати, притом, что если отправить документ из самого Excel все было нормально.

Путем проб и ошибок, танцев с бубнами и увлекательным чтением гугла я выяснил, области печати игнорируется при вызове этого метода и печати в php, C#, но почему то при использовании VBScript все работает как надо. Чем это вызвано я, к сожалению, так и не выяснил.

И так, было решено из PHP открывать VBS скрип и уже из него преобразовывать excel в pdf. Да, это тоже костыль, но не такой неуклюжий как виртуальный принтер.

Вот получившийся скрипт:

Dim XL
Dim XLWkbk
Dim ObjArgs
Dim paramSourceBookPath
Dim paramExportFilePath

set objargs = wscript.arguments
if objArgs.count exec(APPLICATION_SCRIPT_FOLDER.’\excel.vbs C:\tmp\test.xlsx C:\tmp\test.pdf»);

В сухом остатке мы имеем не совсем красивый, но 100% рабочий метод по преобразованию Excel в PDF, который гарантирует результат «Как на печати» без подводных камней.

Источник

How to Convert Excel to PDF Using JavaScript

In this post, you’ll learn how to convert Excel files to PDFs in your JavaScript application using PSPDFKit’s XLSX to PDF JavaScript 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.

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

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:

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 .

Next, 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.js . This is the file where you’ll keep your code.

Your folder structure will look like this:

Step 4 — Installing Dependencies

To get started converting PDF pages, you first need to install the following dependencies:

axios — This package is used for making REST API calls.

Form-Data — This package is used for creating form data.

Use the command below to install both of them:

Step 5 — Writing the Code

Now, open the processor.js file and paste the code below into it:

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

Code Explanation

Here, you have a form variable that contains the instructions for the API. You’re using createReadStream to read the input PDF file. You then have a function, axios.post() , that’ll make the POST request to the Excel to PDF API.

The response of the API is stored in the processed_documents folder.

Output

To execute the code, use the following command:

On the successful execution of the code, you’ll see a new processed file named result.pdf in the processed_documents folder.

The folder structure will look like this:

Final Words

In this post, you learned how to easily and seamlessly convert Excel files to PDF documents for your JavaScript application using our Excel to PDF JavaScript 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.

Источник

VBA Excel. Сохранение книг и листов в PDF

Сохранение в PDF книги Excel, группы листов, одного листа или отдельного диапазона с помощью кода VBA. Метод ExportAsFixedFormat. Примеры экспорта.

Метод ExportAsFixedFormat

Метод ExportAsFixedFormat сохраняет рабочую книгу Excel или выбранную группу листов этой книги в один PDF-файл. Чтобы экспортировать каждый лист в отдельный файл, необходимо применить метод ExportAsFixedFormat к каждому сохраняемому листу.

Синтаксис

Expression – это выражение, представляющее объект Workbook, Worksheet или Range.

Параметры

Единственный обязательный параметр – Type, остальные можно не указывать – в этом случае будут применены значения по умолчанию.

Параметр Описание
Type Задает формат файла для экспорта книги или листа:
xlTypePDF(0) – сохранение в файл PDF;
xlTypeXPS(1) – сохранение в файл XPS*.
FileName Задает имя файла. При указании полного пути, файл будет сохранен в указанную папку, при указании только имени – в папку по умолчанию (в Excel 2016 – «Документы»). Если имя не задано (по умолчанию), файл будет сохранен с именем экспортируемой книги.
Quality Задает качество сохраняемых электронных таблиц:
xlQualityMinimum(1) – минимальное качество;
xlQualityStandard(0) – стандартное качество (по умолчанию).
IncludeDocProperties Включение свойств документа Excel в PDF:
True(1) – включить;
False(0) – не включать;
мне не удалось обнаружить разницу и значение по умолчанию.
IgnorePrintAreas Указывает VBA, следует ли игнорировать области печати, заданные на листах файла Excel:
True(1) – игнорировать области печати;
False(0) – не игнорировать области печати (по умолчанию).
From** Задает номер листа книги Excel, с которого начинается экспорт. По умолчанию сохранение в PDF начинается с первого листа книги.
To** Задает номер листа книги Excel, на котором заканчивается экспорт. По умолчанию сохранение в PDF заканчивается на последнем листе книги.
OpenAfterPublish Указывает VBA на необходимость открыть созданный файл PDF средством просмотра:
True(1) – открыть файл PDF для просмотра;
False(0) – не открывать файл PDF для просмотра (по умолчанию).
FixedFormatExtClassPtr Указатель на класс FixedFormatExt (игнорируем этот параметр).

* XPS – это редко использующийся фиксированный формат файлов, разработанный Microsoft, который похож на PDF, но основан на языке XML.
** Применимо только к книге (Workbook.ExportAsFixedFormat), при экспорте листа (Worksheet.ExportAsFixedFormat) указание параметров From и/или To приведет к ошибке.

Примеры экспорта в PDF

Сохранение в PDF книги Excel

Экспорт всей книги

Если вы указываете путь к файлу, он должен существовать, иначе VBA сохранит файл с именем и в папку по умолчанию («ИмяКниги.pdf» в папку «Документы»).

Экспорт части книги

Этот способ позволяет сохранить в PDF группу листов, расположенных подряд:

Источник

Convert Excel to PDF Using Python

Python is a high-level, general-purpose, and very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry.

In this article, we will learn how to convert an Excel File to PDF File Using Python

Here we will use the win32com module for file conversion.

What is win32com?

Python extensions for Microsoft Windows Provide access to much of the Win32 API, the ability to create and use COM objects, and the Pythonwin environment.

Approach:

  • First, we will create a COM Object Using Dispatch() method.
  • Then we will read the Excel file pass “Excel.Application” inside the Dispatch method
  • Pass Excel file path
  • Then we will convert it into PDF using the ExportAsFixedFormat() method

ExportAsFixedFormat():- The ExportAsFixedFormat method is used to publish a workbook in either PDF or XPS format.

ExportAsFixedFormat (Type, FileName, Quality, IncludeDocProperties, IgnorePrintAreas, From, To,

Input:

EXCEL FILE

Below is the Implementation:

Источник

How to save Excel as PDF with VBA (10 examples)

Since Excel 2010, it has been possible to save Excel as PDF. The PDF format was then and continues to be, one of the most common file formats for distributing documents.

The code examples below provide the VBA macros to automate the creation of PDFs from Excel using the ExportAsFixedFormat method. This means you do not require a PDF printer installed, as Excel can print directly to a PDF document.

The example codes can be used independently or as part of a larger automation process. For example, check out this post to see an example of how to loop through a list and print a PDF for each item: Create multiple PDFs based on a list

Rather than going from Excel to PDF, you might want to go the other way; from PDF to Excel. Check out these posts for possible solutions for that scenario:

Download the example file: Click the link below to download the example file used for this post:

Saving Excel workbooks, sheets, charts, and ranges as PDF

This section contains the base code to save Excel as PDF from different objects (workbooks, worksheets, ranges, and charts). From a VBA perspective, it is the ExportAsFilxedFormat method combined with the Type property set to xlTypePDF that creates a PDF.

Save active sheet as PDF

The following code saves the selected sheets as a single PDF.

Save active workbook as PDF

Use the following macro to save all the visible sheets from a workbook.

Save selection as PDF

Sometimes, we only want to save a small part of a worksheet to a PDF. The following code prints only the selected cells.

Save a range as PDF

The macro below saves a specified range as a PDF.

Save a chart as PDF

The VBA code below saves a specified chart as a PDF.

Rather than naming a specific chart, the macro could run based on the active chart. Change this:

Adapting the code to your scenario

To adapt the code examples to your specific needs, you should adjust certain lines of code.

Change the save location

To save the file in the correct location, change this list of code:

If you would prefer the save location to be included in a cell, change the code to reference the sheet and cell containing the file path.

Change the worksheet

In this line of code, change the text “Sheet1” to the sheet name in your workbook.

Change the range

The following line of codes references the range to be printed to PDF.

Change the chart

To print a chart to PDF, change the chart’s name in the following line of code.

If you are unsure of the chart name, it is shown in the Name box when the chart is selected.

Notes for saving PDF documents

While the Filename property is optional, it is important to know where the file is saved.

  • If the Filename property is not provided, the PDF saves in your default folder location using the Excel workbook’s name with the .pdf file extension.
  • Where a file name is provided, but not a file path, the document saves in your default folder location with the name provided.
  • When the .pdf file extension is not provided, the suffix is added automatically.
  • If a PDF exists in the specified save location, the existing file is overwritten. Therefore, it may be necessary to include file handling procedures to prevent overwriting existing documents and handling errors.
  • To save as an XPS document format, change xlTypePDF for xlTypeXPS.

Selecting specific worksheets before saving as PDF

If more than one worksheet is active, the PDF created includes all the active sheets. The following code selects multiple worksheets from an array before saving the PDF.

In the code above, an array is used to select the specific sheets. Alternatively, the Split array function with a text string could provide a more dynamic solution. This method is covered here: VBA Arrays.

Looping and saving as separate PDFs

To save multiple PDFs quickly, we can use VBA to loop through sheets or charts and save each individually.

Loop through sheets

The following macro loops through each worksheet in the active workbook and saves each as its own PDF. Each PDF is saved in the same folder as the workbook, where each PDF’s name is based on the worksheet’s name.

Loop through selected sheets

The following macro loops through only the selected worksheets in the active workbook and saves each as its own PDF.

Loop through charts

The following code loops through each chart on the active sheet and saves each as a separate PDF.

Other PDF print options

When using ExportAsFixedFormat, there are other optional settings available:

VBA Save to PDF Example using all the options

The code below demonstrates how to use all the options within a single macro. These options can be flexed to meet your requirements.

Other fixed formats available (xlTypeXPS)

The Type property can also create XPS documents when it is set to xlTypeXPS rather than xlTypePDF. XPS is Microsoft’s fixed file format; it is similar to PDF but based on the XML language. It is rarely used in the real world but is an option if required.

Conclusion

Learning how to save Excel as PDF is a good time investment. Each of these code snippets on its own is useful. However, the code examples above can be used in other automation to create even more time-saving.

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).

Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:

Источник

How can I convert Excel documents (files) to PDF in an automated fashion?
I am trying to adapt the solution found here to Excel. So far I have this:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var docPath = WScript.Arguments(0);
docPath = fso.GetAbsolutePathName(docPath);

var pdfPath = docPath.replace(/.xls[^.]*$/, ".pdf");
var objExcel = null;

try
{
    WScript.Echo("Saving '" + docPath + "' as '" + pdfPath + "'...");

    objExcel = new ActiveXObject("Excel.Application");
    objExcel.Visible = false;

    var objExcel = objExcel.Workbooks.Open(docPath);

    var wdFormatPdf = 17;
    objExcel.SaveAs(pdfPath, wdFormatPdf);
    objExcel.Close();

    WScript.Echo("Done.");
}
finally
{
    if (objExcel != null)
    {
        objExcel.Quit();
    }
}

I get this output:

Saving 'somefile.xlsx' as 'somefile.pdf'...
Done.
..SaveXLSXAsPDF.js(27, 9) (null): The object invoked has disconnected from its clients.

A PDF file is created but it is invalid and won’t open in a reader. I’m thinking that perhaps format 17 isn’t the right one for Excel. Does anyone know the right number or how to get this working?

Edit: I found mention of the correct number here (57) but now I get this error:

r:WebRomanSaveXLSXAsPDF.js(27, 13) Microsoft JScript runtime error: Class doesn't support Automation

Community's user avatar

asked Mar 27, 2013 at 22:55

neverfox's user avatar

0

You’re clobbering objExcel on line 15:

var objExcel = objExcel.Workbooks.Open(docPath);

Those lines of code need to use a different variable, e.g.:

var objWorkbook = objExcel.Workbooks.Open(docPath);

var wdFormatPdf = 57;
objWorkbook.SaveAs(pdfPath, wdFormatPdf);
objWorkbook.Close();

answered Mar 27, 2013 at 23:15

ernie's user avatar

ernieernie

6,33822 silver badges28 bronze badges

1

Try to use .ExportAsFixedFormat property instead of .SaveAs. First one is suitable for creating PDF files in Excel but not SaveAs which doesn’t support PDF format.

I guess you would need something like this:

objExcel.ExportAsFixedFormat(0, pdfPath)

answered Mar 27, 2013 at 23:17

Kazimierz Jawor's user avatar

Kazimierz JaworKazimierz Jawor

18.8k7 gold badges35 silver badges55 bronze badges

3

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Python is a high-level, general-purpose, and very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry.

    In this article, we will learn how to convert an Excel File to PDF File Using Python

    Here we will use the win32com module for file conversion.

    What is win32com?

    Python extensions for Microsoft Windows Provide access to much of the Win32 API, the ability to create and use COM objects, and the Pythonwin environment.

    pip install pywin32

    Approach:

    • First, we will create a COM Object Using Dispatch() method.
    • Then we will read the Excel file pass “Excel.Application” inside the Dispatch method
    • Pass Excel file path
    • Then we will convert it into PDF using the ExportAsFixedFormat() method

    ExportAsFixedFormat():- The ExportAsFixedFormat method is used to publish a workbook in either PDF or XPS format.

    Syntax:

    ExportAsFixedFormat (Type, FileName, Quality, IncludeDocProperties, IgnorePrintAreas, From, To, 

    OpenAfterPublish, FixedFormatExtClassPtr)

    Excel File click here

    Input:

    EXCEL FILE

    Below is the Implementation:

    Python3

    from win32com import client

    excel = client.Dispatch("Excel.Application")

    sheets = excel.Workbooks.Open('Excel File Path')

    work_sheets = sheets.Worksheets[0]

    work_sheets.ExportAsFixedFormat(0, 'PDF File Path')

    Output:

    PDF FILE

    Like Article

    Save Article

    Понравилась статья? Поделить с друзьями:
  • Excel to pdf net core
  • Excel to pdf library
  • Excel to pdf editor
  • Excel to pdf converter offline
  • Excel to pdf apk