1

I installed Libreoffice on my win system and able to convert the .docx file to pdf.

import os
import sys

newdir = os.path.abspath(os.path.join(os.path.dirname(__file__)))
if not os.path.exists(newdir):
    os.makedirs(newdir)

file_name = os.path.join(newdir, 'test.docx')
print(file_name)
pdf_filename = file_name.split(".docx")[0] + ".pdf"
pdf_file = os.path.join(pdf_filename)

from subprocess import Popen

if sys.platform == 'darwin':
    LIBRE_OFFICE = '/Applications/LibreOffice.app/Contents/MacOS/soffice'
elif sys.platform == 'win32':
    LIBRE_OFFICE = 'C:/Program Files/LibreOffice/program/soffice'
else:
    LIBRE_OFFICE = 'libreoffice'


def convert_to_pdf(input_docx, out_folder):
    p = Popen([LIBRE_OFFICE, '--convert-to', 'pdf', '--outdir',
               out_folder, input_docx])
    print([LIBRE_OFFICE, '--convert-to', 'pdf', input_docx])
    out = p.communicate()


sample_doc = file_name
out_folder = newdir
convert_to_pdf(sample_doc, out_folder)

The pdf is not aligned properly and the left and right margin is also missing. Can anyone please tell if we can improve or maintain the alignment and styling in libreoffice while converting a docx file to pdf ?

ninjacode
  • 318
  • 2
  • 18
  • 1
    Much depends on the quality of formatting of the original file. Yes, you can get better results. For example, you can very complicate `convert_to_pdf` - don't use `--convert-to`, but open the file, set the desired formatting parameters and [**export to PDF**](https://ask.libreoffice.org/t/how-i-export-pdf-using-macro/38445/2). Another possible solution is to use not LibreOffice, but MS Word (also does not guarantee an ideal result). – JohnSUN Nov 29 '21 at 10:43
  • @k-j I want to make my code work on all the platforms. This piece of code is part of a big project where we want to convert the docx to pdf. Locally, we use win and mac systems but the dev/prod servers are linux based. Most of the python's docx to pdf converter modules work only on win/mac so I went for libreoffice but here I'm facing the alignment issues. – ninjacode Nov 29 '21 at 11:12

0 Answers0