Конвертировать php в word
Генерация документов в doc, excel, 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 у меня возникли затруднения. Поэтому на мой взгляд подход трудно будет применять для генерации сложных печатных форм, таких как счет-фактура.
Конвертер HTML в WORD
Конвертируйте HTML в Word онлайн бесплатно с любого устройства.
Хотите сообщить об этой ошибке на форуме Aspose, чтобы мы могли изучить и решить проблему? Когда ошибка будет исправлена, вы получите уведомление на email. Форма отчета
Приложение для просмотра документов на Android
Конвертировать HTML в Word онлайн
Используйте форматы HTML и Word по максимуму. Мы предоставляем бесплатный Конверте HTML в Word. Наше онлайн-приложение создает DOCX из HTML с высокой скоростью и профессиональным качеством. Алгоритм преобразования позволяет конвертировать HTML во многие популярные файловые форматы.
Лучший бесплатный конвертер HTML в Word
Конвертировать HTML в Word высочайшего качества в любом браузере. Вам не нужно устанавливать какое-либо дополнительное программное обеспечение, такое как Microsoft Word, OpenOffice или Acrobat Reader. Попробуйте прямо сейчас конвертировать HTML в Word онлайн. Вы можете использовать его совершенно бесплатно.
Сохранить HTML как Word с высокой скоростью
Преобразование HTML выполняется быстро и легко. Выполните следующие простые шаги, чтобы преобразовать HTML файл в Word формат. Чтобы преобразовать HTML в Word, перетащите HTML в поле загрузки, укажите параметры преобразования и нажмите кнопку КОНВЕРТИРОВАТЬ. Посмотрите, как ваше HTML превратится в DOCX в течение минуты. Выходное содержимое и форматирование будут идентичны исходному документу.
Программная платформа Aspose Words
Онлайн-приложение Conversion создано на базе программной платформы Aspose Words. Наша компания разрабатывает современные высокопроизводительные решения обработки документов для различных ОС и языков программирования.
Экспорт из PHP в DOC
не могу сделать это:
НО ПОШЛО ТАКОЕ, И ДАЖЕ ПОКАЗАЛО ВЕРСИЮ 15
кто что знает? Единственный выход ставить более раннией Word?
нужен именно DOC, а не DOCx
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Экспорт в pdf, doc
Возможно ли в Silverlight генерировать документы pdf, doc, тоесть знает ли ктонибудь готовые.
Экспорт данных в Doc документ
Доброго времени суток! Создаю программу-тест по психологии. Все данные теста хранятся в глобальных.
Экспорт в doc или в pdf
добрый день, у меня еще очень небольшой экспириенс в asp.net, поэтому прошу помощи. итак, нужно.
А как верно не пойму?
Сейчас если в IE запускаю вообще 500 ошибка показывает..
уже по всякому перепробовал во нашел
Добавлено через 6 минут
Включил ошибки на РНР
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Warning: com::com() [com.com]: Type library constant emptyenum is already defined in C:\www\htdocs\msword\index.php on line 3
Fatal error: Uncaught exception ‘com_exception’ with message ‘Source: Microsoft Word
Description: Ошибка команды’ in C:\www\htdocs\msword\index.php:7 Stack trace: #0 C:\www\htdocs\msword\index.php(7): variant->SaveAs(‘\hw.doc’, 8) #1
HTML to Word with PHP
HTML to Word
The conversion of HTML into Word is one of the most requested functionalities of phpdocx. PHP was born as a server tool for the generation of dynamical HTML pages, so it is no wonder that many of our phpdocx users are pretty familiar with that type of task and they want to take advantage of those skills for the generation of Word documents.
phpdocx offers pretty sophisticated ways to include HTML formatted content into a Word document. The purpose of this tutorial is to offer a detailed account on how one can do it and how to get the most of it.
There are currently two methods to include HTML into a Word document generated from scratch (the case of templates will be treated further below) with phpdocx:
The first one uses internally the «alternative content» element available in the OOXML standard (on which Word is based) and it is simple to use although it has two main drawbacks:
That said, it may be an interesting option if none of the above represents an issue for a given application.
In what follows we will concentrate in the embedHTML method and the replaceVariableByHTML (its avatar for working with Word templates).
The main advantages of the embedHTML methods are summarised in:
And once again with a single line of PHP code.
To get the best DOCX output these methods provide, please install and enable PHP Tidy and PHP mbstring extensions on your server.
Let us first offer a few simple examples that illustrate the most elementary procedures:
Simple HTML code
The code needed to insert some plain HTML is as simple as this:
Let us first offer a few simple examples that illustrate the most elementary procedures:
External HTML source
Sometimes one may need to get the HTML and CSS from existing external files but as we will now show this also turns to be extremely simple.
Let us assume that the HTML code above proceeds from an external HTML page: simpleHTML.html that links to a CSS stylesheet: styles.css.
Then the following code will render exactly the same results:
Notice that the only differences are:
HTML code embedded within a Word table
It may well be that you choose not to embed directly the HTML code into the document but rather insert it within another document element like a table or a header/footer.
This can be achieved in a very simple way using the WordFragment class.
You may modify slightly the previous example:
Embedding images
To include images is equally simple. One may choose to include the images within the document (with the option downloadImages set to true) or keep them as an externally linked resource (in that case you should make sure that the image is available to the final users).
A simple example that makes use of this simple web page with an image reads as follows:
Notice that, as in this case you have not declared the width and height attributes of the image, phpdocx reads its properties from the image header and inserts it with a resolution of 96 dpi (default resolution). One may, of course, choose custom width and height to obtain the desired results.
phpdocx parses all the most commonly used HTML tags and attributes.
It is important to take into account that the HTML and OOXML that Word is based on have different goals so at some points the translation from one to the other should include certain compromises that are not universally valid for all applications. Fortunately it is not difficult to find convenient workarounds that offer a close to perfect Word rendering.
The list of currently parsed HTML elements include:
Block type HTML elements
Inline type HTML elements
HTML web form elements
Currently almost all CSS properties that are applicable to a document, are parsed and translated into their Word counterparts.
In order to achieve the best possible results it is important to know how these CSS properties are applied and their known limitations regarding the final document rendering.
The list of currently parsed CSS styles include:
Border styles and background color
The following border properties are parsed:
Margins and paddings
The concept of padding has not a general direct counterpart in Word so it is usually interpreted as extra margin space.
Page break properties
This properties are partially supported:
Font and text properties
The units may be pixels, points or ems and the colors follow the same scheme as above. The suported properties include:
Positioning
phpdocx tries to adapt as best as possible the positioning properties of elements to equivalent Word properties. If you need to position precisely elements in the resulting Word document the best and simplest way is to do it with tables.
You may also instruct phpdocx to parse divs as tables (see, for example, above) or to parse floats with the «parseFloats» set to true (image floats are always parsed by default).
In any case results are usually pretty good and cover all but the most sophisticated examples.
The parsed properties include:
Lists
phpdocx handles pretty well the rendering of HTML lists and their associated CSS styles. Nevertheless, if you want to use bullets beyond the most standard ones you should call the phpdocx embedding HTML methods in conjunction with the createListStyle method (by setting the ‘customListStyles’ option to true) to obtain the desired results.
In order to do so one should create a custom style that mimics the HTML result and give it the same name that is given in the HTML code for the corresponding class or id attribute. phpdocx will automatically choose the corresponding formatting (bullets, indents, etcetera) previously defined.
The following code illustrates how to create a lower letter and roman style list style and use it with HTML:
In any case results are usually pretty good and cover all but the most sophisticated examples.
In case that one does not bother to define any custom list style, the corresponding CSS list style property is parsed as follows:
HTML Extended, available in Premium licenses, include additional options to generate lists with different styles on its levels.
The following example creates a custom list styles with two different styles for the same level, applied to an HTML:
One of the nicest features of the embedHTML method is that it allows to apply customized Word formatting for paragraphs and tables.
One may write plain HTML with little or none styling and yet generate a very sophisticated Word document.
The default base template already includes all standard Word styles for headings, paragraphs and tables. You may get all the available styles via the phpdocx parseStyles method.
Of course, you may choose a different base template that better suits your needs or even explicitely import styles from other DOCX via the phpdocx importStyles method.
Let us now go over a simple example that illustrate this functionality:
Notice that we have set the option strictWordStyles to true so the HTML parser will ignore the CSS properties and will apply exclusively the selected Word styles.
If one removes the option strictWordStyles or set it to false (its default value), phpdocx will try to combine the Word and HTML styles.
phpdocx adds some default styles when the strictWordStyles option is set as false. The addDefaultStyles option prevents adding these default styles.
Another useful functionality of the embedHTML method is the possibility to filter the HTML content included in the Word document.
One may want to reuse HTML code that has been generated with a different goal in your Word document. A typical example is given by the contents of an existing web page from which you just want to extract its contents without menus or navigation that does not really fit into a Word document.
The filtering can be done in two different ways, which are:
Basic expressions
One can select a set of HTML elements by tag, id or class (’ ’, ‘#myId’ or ‘.myClass’) in a very simple way as follows:
Using XPath expressions
One may choose to filter by more complex expressions that should take the form of valid PHP XPath expressions.
For example, if in the previous example we would have set up the filter option to: //p[@class=»heading2″]|//ul|//table we would have obtained instead a Word document that will only include the paragraph with class heading2, the unordered list and the table.
Besides all the options that have been carefully analysed before, there are are other general options that we now pass to comment briefly.
phpdocx includes a base CSS that applies to all HTML contents set to be converted. Those default styles can be overwritten with the styles added in the HTML or with a modification of the template/html.css file, available in every package.
All the preceding examples have their match in the case we are working with templates by means of the replaceVariableByHtml method.
All the available options are the same as before although we have to give two extra pieces of extra info, namely:
A short example will illustrate it better.
The following code:
Premium licenses include HTML Extended and CSS Extended modes to invoke phpdocx methods with custom HTML tags and apply custom styles not supported by standard HTML tags and CSS styles.
Thus, it is possible to insert headers, footers, comments, table of contents, cross-references, sections and many other contents and styles. All of it integrated with the supported HTML tags and CSS styles.
HTML Extended and CSS Extended have an extra set of methods and options designed to make conversions more flexible and efficient:
An easy example of use of HTML Extended would be the creation of a header and footer:
Or adding contents by mixing HTML and HTML Extended:
PHP: Как сохранить HTML в DOC
При разработке онлайн-проектов часто возникает необходимость сохранить html-страничку в виде документа, который можно использовать отдельно, например, отправить по электронной почте, просматривать и редактировать оффлайн. Удобным способом сохранения html таким образом является экспорт в один из наиболее часто используемых текстовых форматов — doc.
Для экспорта html документа в формат doc можно воспользоваться открытым бесплатным php-модулем «html_to_doc». С его помощью можно сохранить html в документ doc, который будет корректно обработан текстовым редактором MS Word. Если в html-страничке присутствуют изображения, они будут встроены в документ doc.
Установка:
Скачайте файл ExportToWord.inc.php и включите его в свой проект.
Весь код модуля размещается в одном файле ExportToWord.inc.php. Достаточно разместить его в директории проекта, ничего дополнительно устанавливать не нужно.
В самом файле для корректной работы нужно отредактировать следующие параметры:
Использование:
С помощью директивы require или include подключите модуль ExportToWord.inc.php в код своего проекта.
Для сохранения html-кода в документ doc вызовите функцию ExportToWord::htmlToDoc() из подключенного модуля, передав в параметрах собственно html, таблицу стилей css и имя файла с путем, по которому нужно поместить готовый документ doc.
