import base64 from odoo import models, api import subprocess import tempfile import os import logging _logger = logging.getLogger(__name__) class AttachmentConverter(models.AbstractModel): _name = 'ir.attachment.converter' _description = 'Attachment Converter' @api.model def convert_to_pdf(self, attachment): if attachment._get_preview_type() != 'office': return False with tempfile.NamedTemporaryFile(suffix='.docx', delete=False) as doc_file: doc_file.write(base64.b64decode(attachment.datas)) doc_path = doc_file.name pdf_path = doc_path + '.pdf' try: # Using LibreOffice for conversion subprocess.run([ 'libreoffice', '--headless', '--convert-to', 'pdf', '--outdir', os.path.dirname(doc_path), doc_path ], check=True) with open(pdf_path, 'rb') as pdf_file: return pdf_file.read() except Exception as e: _logger.error(f"Conversion failed: {e}") return False finally: # Clean up temp files if os.path.exists(doc_path): os.unlink(doc_path) if os.path.exists(pdf_path): os.unlink(pdf_path)