Я извлек встроенные файлы с помощью 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]
Я извлек встроенные файлы с помощью lxml docx в содержимое xml и проверил наличие слов/вложений. Я могу извлечь файлы docx, xslx, поскольку они сохранены в том же формате в xml. Но для файлов pdf и zip он извлекается из встроенных файлов как формат .bin. Я попробовал извлечь файлы PDF из файлов формата .bin и сохранить. Но я не могу сделать то же самое для zip-файла. В настоящее время внутри моего zip-файла есть файл изображения (tif), но это может быть что угодно в формате PDF или что-то еще, что мне нужно извлечь в формате .zip и сохранить. [code]def extract_embedded_files_from_docx(self,docx_file): """ Extracts embedded files from a DOCX file. """ embedded_files = {}
# 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
# 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)
Я создал новый документ Word на основе существующего документа Word в проекте надстройки Word Blazor. Я хочу добавить содержимое в новый документ Word, а также загрузить панель задач в новый документ Word, аналогичный существующей панели задач Word....
Я создал новый документ Word на основе существующего документа Word в проекте надстройки Word Blazor. Я хочу добавить содержимое в новый документ Word, а также загрузить панель задач в новый документ Word, аналогичный существующей панели задач Word....
В приведенном ниже коде я использую библиотеку XSLX для группировки моей строки с уровнями структуры, с которыми она работает - петь, но я хочу сделать + петь с уже свернутым.
let a = 4, b = 11; for (let indexrow = 0; indexrow <...
Задание состоит в том, чтобы извлечь таблицу из отсканированного PDF-файла. Я пробовал использовать Camelot/tabula, но ничего не помогло.
Есть предложения по извлечению таблиц?
Пример