php excel to pdf

Генерация документов в doc, excel, pdf и других форматах на сервере

Выгрузка отчетов в различных форматах — типовая задача для многих проектов. И сейчас есть немало инструментов для этого. Среди них есть интересный вариант, который применяется, как мне кажется, не часто, но он однозначно стоит внимания. Потому что позволяет получить документ в нужном формате буквально одной командой. О нем и расскажу.

php excel to pdf. Смотреть фото php excel to pdf. Смотреть картинку php excel to pdf. Картинка про php excel to pdf. Фото php excel to pdf

Я буду не многословен и сразу скажу, что речь идет о конвертере, встроенном в пакет LibreOffice. Вы можете запустить конвертацию из консоли, чтобы увидеть как это работает:

Эта команда конвертирует файл html.html в pdf файл. Количество поддерживаемых форматов впечатляет.

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

Запуск конвертации из PHP

Для установки конвертера на сервере придется установить пакет libreoffice-core:

Чтобы было удобно работать с утилитой из PHP, я написал обертку.

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

Для работы с оберткой подключаем ее к своему проекту через composer:

Использовать ее можно так:

В результате будет сформирован docx файл. Больше примеров можно найти на гитхабе.

Разумеется, в качестве бонуса можно запускать конвертацию в другую сторону — из doc в html и отображать содержимое офисных документов в браузере. Качество конвертации будет не всегда на высоте, но для каких-то случаев вполне подойдет.

Несколько граблей

Будет полезно рассказать про несколько особенностей, с которыми я столкнулся при работе с этой утилитой.

1. Применение CSS стилей. При преобразовании html в нужный формат имейте ввиду, что такая запись воспринимается корректно:

А такие записи будут обработаны точно так же, как если бы class мы совсем не указали:

2. При преобразовании html в нужный формат не всегда срабатывают описания стилей и иногда приходится экспериментировать, чтобы заработало. Например, так не работает:

3. Одно и то же преобразование можно выполнять с помощью разных конвертеров. При этом результат будет существенно отличаться. Если у вас на выходе получится не очень красивый документ, попробуйте принудительно задать используемый модуль, например:

4. Можно ли настроить ширину строк в таблице — для меня пока загадка. И в целом со стилизацией таблицы при преобразовании html в docx или pdf у меня возникли затруднения. Поэтому на мой взгляд подход трудно будет применять для генерации сложных печатных форм, таких как счет-фактура.

Источник

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

I am looking for a way to convert Word and Excel files to PDF using PHP.

The reason for this, is I need to be able to combine files of various formats into one document. I know that if I am able to convert everything to PDF I can then merge the PDFs into one file using PDFMerger (which uses fpdf).

I am already able to create PDFs from other file types / images, but am stuck with Word Docs. (I think I would possibly be able to convert the Excel files using the PHPExcel library that I already use to create Excel files from html code).

I do not use the Zend Framework, so am hoping that someone will be able to point me in the right direction.

Alternatively, if there is a way to create image (jpg) files from the Word documents, that would be workable.

12 Answers 12

I found a solution to my issue and after a request, will post it here to help others. Apologies if I missed any details, it’s been a while since I worked on this solution.

The first thing that is required is to install Openoffice.org on the server. I requested my hosting provider to install the open office RPM on my VPS. This can be done through WHM directly.

Now that the server has the capability to handle MS Office files you are able to convert the files by executing command line instructions via PHP. To handle this, I found PyODConverter: https://github.com/mirkonasato/pyodconverter

I created a directory on the server and placed the PyODConverter python file within it. I also created a plain text file above the web root (I named it «adocpdf»), with the following command line instructions in it:

This checks that the openoffice.org libraries are running and then calls the PyODConverter script to process the file and output it as a PDF. The 3 variables on the first three lines are provided when the script is executed from with a PHP file. The delay («sleep 5s») is used to ensure that openoffice.org has enough to time to initiate if required. I have used this for months now and the 5s gap seems to give enough breathing room.

The script will create a PDF version of the document in the same directory as the original.

Finally, initiating the conversion of a Word / Excel file from within PHP (I have it within a function that checks if the file we are dealing with is a word / excel document).

OK, that’s it! Hopefully this will be useful to someone and save them the difficulties and learning curve I faced.

Источник

How to configure phpexcel for pdf

I’m using Codeigniter and WAMP.

I downloaded PHPExcel, and it’s on my C: directory.

Later i copied Classes: PHPExcel (folder) and PHPExcel.php to my codeigniter’s third party folder.

Then, inside Codeigniter’s Application, Libraries, i created a file named pdf.php and copied in there the code from the original PHPExcel docs (21pdf.php)

pdf.php

I don’t really know how to configure it, my brain is burned right now. Any help would be very appreciated!

php excel to pdf. Смотреть фото php excel to pdf. Смотреть картинку php excel to pdf. Картинка про php excel to pdf. Фото php excel to pdf

2 Answers 2

ok so now i have this thing working, took me several days but finally achieved it.

In order to configure phpexcel in Codeigniter for generating pdf reports i had to:

2). Then, inside application/libraries i created a file excel.php with the class constructor:

3). nex to move on to pdf. First you should choose which library you want to use. I chose to use dompdf https://github.com/dompdf/dompdf and install this in application/libraries

4). created a file name pdf.php (place it where you want) and in it i put this (based on the examples given in the official phpexcel docs: 21pdf.php and 01simple-download-pdf.php that you can find in the test folder in PHPExcel):

‘dompdf_0-6-0_beta3’ is the name of the folder that contains the library for rendering into pdf

I posted this question when my error was that render library couldn’t be found. That’s why i was trying to use the phpexcel wrapper and not the propper library. So after that had to fight a little bit with the path but then made it.

After that fixed, another error came up: ‘Unable to load PDF Rendering library’ in DomPDF (from PHPExcel). So i found out that this line:

Источник

XLS to PDF API

The API for converting Excel XLS documents to PDF files.

Please Sign In or Sign up for FREE in order to test API request.

String Authentication secret must be provided as a query parameter. If omitted, token must be provided.

String Authentication token must be provided as a query parameter. If omitted, secret must be provided.

File File to be converted. Value can be URL or file content.

Bool Store converted file on our secure server and provides download URL.

Default: False

String Converted output file name without extension. The extension will be added automatically.

Integer Conversion timeout in seconds.

Default: 900

Bool Run conversion job asynchronously.

Default: False

String Conversion job self generated UUID (RFC 4122) used for getting conversion result asynchronously.

String Set WebHook URL to call after asynchronous conversion is finished. Async parameter must be enabled.

String Sets the password to open protected documents.

Bool Set to convert active worksheet. If value is not set all worksheet will be converted.

Default: False

Integer Set worksheet index(number) to convert. If value is not set all worksheet will be converted.

String Set worksheet name to convert. If value is not set all worksheet will be converted.

Collection Page orientation.

Default: default

Values: default, portrait, landscape

Collection Page size.

Default: default

Values: default, letter, lettersmall, tabloid, ledger, legal, statement, executive, a3, a4, a4small, a5, b4, b5, folio, quarto, 10×14, 11×17, note, envelope9, envelope10, envelope11, envelope12, envelope14, csheet, dsheet, esheet, envelopedl, envelopec3, envelopec4, envelopec5, envelopec6, envelopec65, envelopecb4, envelopeb5, envelopeb6, envelopeeurope, envelopem, envelopeusa, fanfoldusa, fanfoldgerman, lfanfoldgerman

Источник

XLSX to PDF API

The API for converting Excel XLSX documents to PDF files.

Please Sign In or Sign up for FREE in order to test API request.

String Authentication secret must be provided as a query parameter. If omitted, token must be provided.

String Authentication token must be provided as a query parameter. If omitted, secret must be provided.

File File to be converted. Value can be URL or file content.

Bool Store converted file on our secure server and provides download URL.

Default: False

String Converted output file name without extension. The extension will be added automatically.

Integer Conversion timeout in seconds.

Default: 900

Bool Run conversion job asynchronously.

Default: False

String Conversion job self generated UUID (RFC 4122) used for getting conversion result asynchronously.

String Set WebHook URL to call after asynchronous conversion is finished. Async parameter must be enabled.

String Sets the password to open protected documents.

Bool Set to convert active worksheet. If value is not set all worksheet will be converted.

Default: False

Integer Set worksheet index(number) to convert. If value is not set all worksheet will be converted.

String Set worksheet name to convert. If value is not set all worksheet will be converted.

Collection Page orientation.

Default: default

Values: default, portrait, landscape

Collection Page size.

Default: default

Values: default, letter, lettersmall, tabloid, ledger, legal, statement, executive, a3, a4, a4small, a5, b4, b5, folio, quarto, 10×14, 11×17, note, envelope9, envelope10, envelope11, envelope12, envelope14, csheet, dsheet, esheet, envelopedl, envelopec3, envelopec4, envelopec5, envelopec6, envelopec65, envelopecb4, envelopeb5, envelopeb6, envelopeeurope, envelopem, envelopeusa, fanfoldusa, fanfoldgerman, lfanfoldgerman

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *