Необходимо извлечь встроенные файлы из документа Word, где в файле доступны pdf, word, xslx, zip.Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Необходимо извлечь встроенные файлы из документа Word, где в файле доступны pdf, word, xslx, zip.

Сообщение Anonymous »

Я извлек встроенные файлы с помощью lxml docx в содержимое xml и проверил наличие слов/вложений. Я могу извлечь файлы docx, xslx, поскольку они сохранены в том же формате в xml. Но для файлов pdf и zip он извлекается из встроенных файлов как формат .bin. Я попробовал извлечь файлы PDF из файлов формата .bin и сохранить. Но я не могу сделать то же самое для zip-файла. В настоящее время внутри моего zip-файла есть файл изображения (tif), но это может быть что угодно в формате PDF или что-то еще, что мне нужно извлечь в формате .zip и сохранить.

Код: Выделить всё

def extract_embedded_files_from_docx(self,docx_file):
"""
Extracts embedded files from a DOCX file.
"""
embedded_files = {}

azure_func = Azure()

blob_data = azure_func.read_file(
file_path=docx_file, is_text_content=False
)

# Open the DOCX file (which is a ZIP archive)
with zipfile.ZipFile(BytesIO(blob_data), 'r') as docx_zip:
# Iterate through files in the DOCX zip to find embedded files
for file in docx_zip.namelist():
if file.startswith('word/embeddings/'):
file_name = os.path.basename(file)
bin_file_data = docx_zip.read(file)
# Check if the file is an oleObject*.bin (which could be PDFs or other file types)
if file_name.startswith('oleObject') and file_name.endswith('.bin'):
# Use python-magic to detect the file type

mime = magic.Magic(mime=True)
file_type = mime.from_buffer(bin_file_data)

if file_type == 'application/CDFV2':
# Open the CDFV2 (OLE) file using olefile
ole = olefile.OleFileIO(BytesIO(bin_file_data))

embedded_file_name = self.extract_file_name_from_ole(ole)

# List the available storages/streams in the CDFV2 file
storages = ole.listdir()
print("Storages in CDFV2 file:", storages)

# Extract from the 'CONTENTS' stream
if ['CONTENTS'] in storages:
# Extract the file content from the 'CONTENTS' stream
file_data = ole.openstream(['CONTENTS']).read()
print(f"Extracted content from 'CONTENTS' stream.")
else:
# Try extracting data from '\x01Ole' or '\x01Ole10Native'
file_data = None
for storage in storages:
if storage in [['\x01Ole'], ['\x01Ole10Native']]:
print(f"Found embedded file in {storage}.  Extracting data...")
file_data = ole.openstream(storage).read()
break
# Use magic to check file type (e.g., PDF, Excel, etc.)
embedded_file_type = magic.Magic(mime=True).from_buffer(file_data)

if embedded_file_type == 'application/octet-stream':
if len(storages) 

Подробнее здесь: [url]https://stackoverflow.com/questions/79251011/need-to-extract-embedded-files-from-word-document-where-pdf-word-xslx-zip-a[/url]
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»