-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_doc_pdf.py
More file actions
63 lines (48 loc) · 1.67 KB
/
convert_doc_pdf.py
File metadata and controls
63 lines (48 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from sys import *
from docx import *
from reportlab.lib.pagesizes import *
from reportlab.pdfgen.canvas import *
import os
def doc_pdf(docpath):
# Ensure the file has a .docx extension
if not docpath.lower().endswith(".docx"):
print("Error: The file must be a .docx file.")
exit(1)
# Check if the input file exists
if not os.path.exists(docpath):
print(f"Error: The file {docpath} was not found.")
exit(1)
# Generate the output PDF path
pdfpath = docpath.rsplit(".", 1)[0] + ".pdf"
try:
# Load the .docx file
doc = Document(docpath)
# Create a PDF canvas
c = Canvas(pdfpath, pagesize=letter)
width, height = letter
# Set the starting position for text
y_position = height - 40
# Loop through the paragraphs in the document
for para in doc.paragraphs:
# If there's enough space on the page, add the paragraph text
if y_position > 40:
c.drawString(40, y_position, para.text)
y_position -= 15 # Move down for the next line
else:
# If we run out of space, create a new page
c.showPage()
y_position = height - 40
c.drawString(40, y_position, para.text)
y_position -= 15
# Save the PDF
c.save()
print(f"PDF saved at -> {pdfpath}")
except Exception as e:
print(f"Error occurred during conversion: {e}")
exit(1)
if __name__ == "__main__":
if len(argv) != 2:
print("Usage: python doc_pdf.py <path_to_doc_file>")
exit(1)
docpath = argv[1]
doc_pdf(docpath)