Не сохраняется word в pdf в питон модулем comtypes
для работы с файлами MS word в python есть расширения Python win32, которые можно использовать в windows. Как сделать то же самое в linux? Здесь есть библиотека?
вы можете сделать вызов подпроцесса антислово. Antiword-это утилита командной строки linux для сброса текста из документа word. Работает довольно хорошо для простых документов (очевидно, он теряет форматирование). Он доступен через apt и, вероятно, как RPM, или вы можете скомпилировать его самостоятельно.
использовать собственный модуль Python docx. Вот как извлечь весь текст из документа:
также проверить Textract который вытягивает вне таблицы etc.
парсинг XML с regexs вызывает ктулу. Не делай этого!
Бенджаминответ довольно хороший. Я только что консолидировался.
поскольку OOo может загружать большинство файлов MS Word безупречно, я бы сказал, что это ваш лучший выбор.
Я знаю, что это старый вопрос, но я недавно пытался найти способ извлечь текст из файлов MS word, и лучшее решение, которое я нашел, было с wvLib:
после установки библиотеки использовать ее в Python довольно просто:
и это все. В основном, мы используем команды.функция getouput для запуска нескольких сценариев оболочки, а именно wvText (который извлекает текст из документа Word и cat для чтения вывода файла). После этого весь текст из документа Word будет находиться в переменной out, готовой к использованию.
надеюсь, это поможет любому, кто имеет аналогичные проблемы в будущем.
однако, если документ имеет сложные таблицы, текстовые поля, встроенные таблицы и т. д., то он может работать не так, как ожидалось. Разработка хороших фильтров MS Word-очень сложный процесс, поэтому, пожалуйста, несите мы, как мы работаем над тем, чтобы правильно открыть документы Word. Если у вас есть документ Word, который не загружается, откройте ошибку и включите документ, чтобы мы могли улучшить импортера.
(Примечание: я разместил это на этот вопрос также, но это кажется актуальным здесь, поэтому, пожалуйста, извините репост.)
теперь это довольно уродливо и довольно хаки, но, похоже, это работает для меня для базового извлечения текста. Очевидно, чтобы использовать это в программе Qt, вам нужно будет создать процесс для него и т. д., но командная строка, которую я взломал:
распаковать файла-P.файлы DOCX: - p = = " распаковать в поток stdout"
grep ' : захватите только строки, содержащие ' - это XML-элемент Word 2007 для "текста", насколько я могу судить)
sed ' s / >/ / g'*: удалить все внутри тегов
grep-v '^[[: space:]]$'*: удалить пустые строки
вероятно, есть более эффективный способ сделать это, но, похоже, он работает для меня на нескольких документах, с которыми я его тестировал.
насколько мне известно, unzip, grep и sed имеют порты для Windows и любого из Unixes, поэтому он должен быть разумно кросс-платформенным. Despit быть немного уродливый Хак;)
Если вы намерены использовать исключительно модули python без вызова подпроцесса,вы можете использовать модуд python zipfile.
ваша строка содержимого, однако, должна быть очищена, один из способов сделать это:
но есть, безусловно, более элегантный способ очистки строки, вероятно, с помощью модуля re. Надеюсь, это поможет.
Я не уверен, что Вам ПОВЕЗЕТ без использования COM. Этот.формат doc смехотворно сложен и часто называется "дампом памяти" Word во время сохранения!
в Swati это в HTML, что хорошо и денди, но большинство документов word не так хорошо!
Это старый вопрос? Я верю, что такого не существует. Есть только те, на которые нет ответа. Этот вопрос остался без ответа или, если хотите, наполовину решен. Ну, методы чтения *.docx (MS Word 2007 и более поздние версии) документы без использования com-взаимодействия все охвачены. Но методы извлечения текста из *.doc (MS Word 97-2000), используя только Python, не хватает. Это сложно? Делать: не совсем, понимать: ну, это другое дело.
когда я не найдите любой готовый код, я прочитал некоторые спецификации формата и выкопал некоторые предлагаемые алгоритмы на других языках.
MS Word (*.doc) файл представляет собой составной файл OLE2. Чтобы не беспокоить вас множеством ненужных деталей, подумайте об этом как о файловой системе, хранящейся в файле. Он фактически использует структуру жира, поэтому определение выполняется. (Хм, может быть, вы можете смонтировать его в Linux. ) Таким образом, вы можете хранить больше файлов в файле, например, фотографии и т. д. То же самое делается в *.docx с помощью ZIP вместо архиве. На PyPI доступны пакеты, которые могут читать OLE-файлы. Как (olefile, compoundfiles. ) Я использовал пакет compoundfiles для открытия *.doc-файл. Однако в MS Word 97-2000 внутренними вложенными файлами являются не XML или HTML, а двоичные файлы. И поскольку этого недостаточно, каждый содержит информацию о другом, поэтому вы должны прочитать хотя бы два из них и разгадать сохраненную информацию соответственно. Чтобы понять полностью, прочитайте PDF-документ, из которого я взял алгоритм.
код ниже очень поспешно составлено и протестировано на небольшом количестве файлов. Насколько я вижу, все работает как задумано. Иногда какая-то тарабарщина появляется в начале, и почти всегда в конце текста. И между ними могут быть какие-то странные символы.
те из вас, кто просто хочет искать текст, будут счастливы. Тем не менее, я призываю всех, кто может помочь улучшить этот код, сделать это.
читать Word 2007 и более поздние файлы, в том числе .docx-файлы, вы можете использовать в Python-docx в пакет:
читать .doc-файлы из Word 2003 и более ранних версий, сделайте вызов подпроцесса антислово. Сначала вам нужно установить antiword:
тогда просто вызовите его из своего скрипта python:
просто опция для чтения файлов " doc " без использования COM:миетта. Должен работать на любой платформе.
I'am tasked with converting tons of .doc files to .pdf. And the only way my supervisor wants me to do this is through MSWord 2010. I know I should be able to automate this with python COM automation. Only problem is I dont know how and where to start. I tried searching for some tutorials but was not able to find any (May be I might have, but I don't know what I'm looking for).
Right now I'm reading through this. Dont know how useful this is going to be.
14 Answers 14
A simple example using comtypes, converting a single file, input and output filenames given as commandline arguments:
You could also use pywin32, which would be the same except for:
For many files, consider setting: word.Visible = False to save time and processing of the word files (MS word will not display this way, code will run in background essentially)
I've managed to get this working for powerpoint documents. Use Powerpoint.Application , Presentations.Open and FileFormat=32 .
I am using a linux server and these libraries dont work in linux.. is there any other way to make it work in linux
You can use the docx2pdf python package to bulk convert docx to pdf. It can be used as both a CLI and a python library. It requires Microsoft Office to be installed and uses COM on Windows and AppleScript (JXA) on macOS.
Just used your package to print my .docx file. It worked like a charm! Couldn't have been simpler to use. Great job!
@Abdelhedihlel Unfortunately, it requires Microsoft Office to be installed and thus only works on Windows and macOS.
(1). The first time when I created the 'Word.Application' object, I should make it (the word app) visible before open any documents. (Actually, even I myself cannot explain why this works. If I do not do this on my computer, the program will crash when I try to open a document in the invisible model, then the 'Word.Application' object will be deleted by OS. )
(2). After doing (1), the program will work well sometimes but may fail often. The crash error "COMError: (-2147418111, 'Call was rejected by callee.', (None, None, None, 0, None))" means that the COM Server may not be able to response so quickly. So I add a delay before I tried to open a document.
After doing these two steps, the program will work perfectly with no failure anymore. The demo code is as below. If you have encountered the same problems, try to follow these two steps. Hope it helps.
Мне поручено преобразовать тонны файлов .doc в .pdf. И единственный способ, которым мой руководитель хочет, чтобы я сделал это, - это использовать MSWord 2010. Я знаю, что смогу автоматизировать это с помощью автоматизации python COM. Проблема только в том, что я не знаю, как и с чего начать. Я попытался найти несколько руководств, но не смог их найти (может быть, мог, но я не знаю, что ищу).
Сейчас я читаю через это . Не знаю, насколько это будет полезно.
Простой пример использования контипов , преобразование одного файла, имена файлов ввода и вывода, заданные в качестве аргументов командной строки:
Вы также можете использовать pywin32 , который будет таким же, за исключением:
Для многих файлов рассмотрите настройку: word.Visible = False для экономии времени и обработки текстовых файлов (MS word не будет отображаться таким образом, код будет работать в фоновом режиме)
Мне удалось заставить это работать для документов PowerPoint. Используйте Powerpoint.Application , Presentations.Open и FileFormat=32 .
Я использую Linux-сервер, и эти библиотеки не работают в Linux .. есть ли другой способ заставить его работать в Linux?
8 лет разработки, и именно этот ответ заставил меня почувствовать себя плохо из-за того, что я не в Windows!
Вы можете использовать docx2pdf пакет python для массового преобразования docx в pdf. Его можно использовать как в качестве интерфейса командной строки, так и в качестве библиотеки Python. Он требует установки Microsoft Office и использует COM в Windows и AppleScript (JXA) в macOS.
Просто использовал ваш пакет для печати моего файла .docx. Оно работало завораживающе! Не могло быть проще в использовании. Отличная работа!
@Abdelhedihlel К сожалению, для него требуется установленный Microsoft Office, поэтому он работает только в Windows и macOS.
(1). В первый раз, когда я создал объект Word.Application, я должен сделать его (приложение слова) видимым, прежде чем открывать какие-либо документы. (На самом деле, даже я сам не могу объяснить, почему это работает. Если я не сделаю этого на своем компьютере, программа выйдет из строя, когда я попытаюсь открыть документ в невидимой модели, тогда объект Word.Application будет удален ОПЕРАЦИОННЫЕ СИСТЕМЫ. )
(2). После выполнения (1) программа иногда будет работать хорошо, но часто может давать сбой. Ошибка сбоя "COMError: (-2147418111, 'Call was rejected by callee.', (None, None, None, 0, None))" означает, что COM-сервер не может ответить так быстро. Поэтому я добавляю задержку перед попыткой открыть документ.
После выполнения этих двух шагов программа больше не будет работать без сбоев. Демо-код приведен ниже. Если вы столкнулись с такими же проблемами, попробуйте выполнить эти два шага. Надеюсь, это поможет.
Have you always wanted to convert Docx files into pdf in a batch? If yes, these python scripts will make your life much more comfortable.
The two methods of which one includes GUI another doesn’t. The following one is slightly different and requires a Word application installed on your system.To install docx2pdf:
The first one will be without GUI:
Explanation: The convert() function takes two arguments that are the abs path of the file you want to convert and where you want to save. You can do batch convert by providing the folder path.
This library also allows using CLI instead of writing a code in a separate file.
To implement this using GUI, you must install PyQt5:
Explanation: There is a lot of theory to cover all the functions used, but we will only see the important ones. You can get more information by checking out the references attached below.
QMimeData belongs to the QtCore module stores data on a clipboard then is used in the drag and drop process.
DragEnterEvent: provides an event sent to the target widget as dragging action enters it.
DragMoveEvent: is used when the drag and drop action is in progress.
DropEvent: is the event that occurs when the drop gets completed.
hasUrls(): Returns true if the object can return a list of URLs; else returns false.
The basic idea is to use PyQt5 to create a GUI, PyQt.QtWidgets to use QListWidget and its functions and PyQt5.QtCore to get the URI-list of the files, basically the location of the file, and then converting the file at this location.
There is also another way to convert Docx files into PDF that requires a word application installed on your system.
Sometimes we would like to convert some docx/doc or word files to PDF without going into large number of steps, which can be very hectic when we are converting docx files to PDF on a daily basis or even on hourly basis or if you want to convert files in batch then it can be quite difficult to do this task.
I came across this issue and tried to automate this process when I used to be in the job hunting phase, where I have to convert my CV and Cover letter to PDF after some necessary updates, some values that keep on changing on a daily basis, which can be quite tedious to change 2–3 values in my cover letter and change the company name and position for the job for each iteration/application. Let’s say you are a jack of all trades and you know many things like Android Development, data analysis and machine learning skills etc. In this case, you have to update a lot of things in your CV and cover letter to make your application a bit more personalized to increase your chances on landing a job.
Note:- I am planning to write an article for people who are in job hunting phase. I will share the script which I have made to automate this whole update process+Conversion in which we have to change some values along with company name and position in our Application.
So is there any harm in wasting your time?
Yes, it’s very important thing that we should focus on our time consuming tasks.
It’s undeniable fact that Python is here to help you in this case. You can make it a script which can update and convert files in just milliseconds.
Method 1:-
If you want a good looking easy to use File picker then you can use this method.
For the file picker dialog, we have to use the tkinter library which is basically a Python GUI library.
Library which is responsible for the conversion of the Word file to pdf is comtypes and for file’s path handling is OS. (Operating system)
So we can prompt a user by opening a dialog by:-
Next Step is to give this filename which has the full path of the input file along with file extension therefore, you don’t need to worry about full path of the file or extension.
Now specify the output path including filename.
Note:-
- Don’t need to specify file extension which is pdf in our case.
- When you are giving paths here, always write ‘r’ before the string to format it.
Now create a object of comtype by:
Open the input file and save it as output file and file-format in our case is 17 which is the code for PDF conversion.
And finally close the doc file object which is the best practice in programming. :)
Second method is same as above, if we don’t want to choose file from the dialog, then we don’t need to use tkinter library, we just have to give the input file path like this:
So for converting the files in batch we have to give all the input files path to our program, so for that we have to take help from glob library.
For fetching all the files from a directory or enlist all the files with a specific extension from a directory, we have to give path of our directory where all our required files reside and write extension name at the end like to specify the extension. This will give you only that type of files.
It will give us list of all file-paths including filenames.
It is pertinent to mention here that we have to specify the output file name also, as we are doing this conversion in “batch” so we have to handle the output file names also, means output file names must be same as the input in order to have full control over the files which is an important step.
So for that we have to take help from regex library which is my personal favourite library and it’s problems are my favourite ones to solve.
glob.glob() will give us a list of filename and its path, but we don’t need full path of the file, we only need the name of the file for naming the output files.
Output of glob.glob()
[‘C:\\Users\\Hp\\Downloads\\Hidden Gem.docx’, ‘C:\\Users\\Hp\\Downloads\\sample (1).docx’, ‘C:\\Users\\Hp\\Downloads\\resume of PI.docx’, ‘C:\\Users\\Hp\\Downloads\\Sources.docx’, ‘C:\\Users\\Hp\\Downloads\\TALK SHOW.docx’]
So we have to extract only filename from the full path.
we will use the regex function which will replace the string with our substitute string upon giving the regular expression. The regular expression which is responsible for removing the filepath is as follow:
re.sub() will help us.
But this will give us filename with its extension but we don’t need the extension as I mentioned earlier. So to remove that we have to use this regex.
Note:-
After running this code, you may see a prompt dialog like this:
Now just select the first option and click OK then close word application afterwards and everything will work perfectly.
Читайте также: