Home > Enterprise >  Python: how do I change page size of a Word document and then print it into PDF?
Python: how do I change page size of a Word document and then print it into PDF?

Time:11-24

I have a bunch of Word documents that I need to reset to the Letter page size (they are all currently 11"x17"). Is there a Python library that I can use to:

  1. Load a Word doc
  2. Set its page size to Letter
  3. Print it into PDF

Seems like docx2pdf can be used to do 1 and 3 but what about 2? And if it can do it, how? Other options?

TIA!

CodePudding user response:

Here's what worked for me at the end:

from docx import Document
from docx.shared import Inches
import os
from docx2pdf import convert

for root, dirs, files in os.walk(r"c:\rootdir"):
  for file in files:
    if file.endswith('.docx'):
        inDocxFN = os.path.join(root, file)

        base = os.path.splitext(inDocxFN)[0]
        outDocxFN = base   '.2.docx'
        outPdfFN = base   '.pdf'
        print("%s TO %s" % (inDocxFN,outPdfFN))

        document = Document(inDocxFN)

        section = document.sections[0]

        section.page_width = 7772400
        section.page_height = 10058400

        # don't want to modify the originals, so create a copy and then generate PDF from it, then delete the copy
        #
        document.save(outDocxFN)

        try:
             convert(outDocxFN,outPdfFN)
        except:
             print("Failed converting %s" % outDocxFN)
             
        try:
             os.remove(outDocxFN)
        except:
             print("Failed deleting %s" % outDocxFN)
         
  • Related