xxxxxxxxxx
import sys
import os
import comtypes.client
wdFormatPDF = 17
in_file = os.path.abspath(sys.argv[1])
out_file = os.path.abspath(sys.argv[2])
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
doc.Close()
word.Quit()
xxxxxxxxxx
import win32com.client as win32
def convert_word_to_pdf(input_file, output_file):
word_app = win32.Dispatch("Word.Application")
word_app.Visible = False
try:
doc = word_app.Documents.Open(input_file)
doc.SaveAs(output_file, FileFormat=17) # 17 represents PDF format
doc.Close()
finally:
word_app.Quit()
# Usage
input_file_path = "path/to/input.docx"
output_file_path = "path/to/output.pdf"
convert_word_to_pdf(input_file_path, output_file_path)
xxxxxxxxxx
from docx import Document
from PyPDF2 import PdfWriter
def convert_word_to_pdf(input_file_path, output_file_path):
# Load the Word document
doc = Document(input_file_path)
# Create a PDF writer
pdf_writer = PdfWriter()
# Iterate through each page of the Word document
for page in doc.pages:
# Extract the content from each page and add it to the PDF writer
pdf_writer.add_page(page)
# Write the PDF content to the output file
with open(output_file_path, 'wb') as output_file:
pdf_writer.write(output_file)
# Usage example
input_doc_file = 'input.docx' # Replace with the actual input Word document file path
output_pdf_file = 'output.pdf' # Replace with the desired output PDF file path
convert_word_to_pdf(input_doc_file, output_pdf_file)
xxxxxxxxxx
import win32com.client as win32
# Define the input Word document and output PDF file paths
input_doc = "path/to/input.docx"
output_pdf = "path/to/output.pdf"
# Create an instance of the Word Application
word_app = win32.gencache.EnsureDispatch("Word.Application")
# Open the input Word document
doc = word_app.Documents.Open(input_doc)
# Save the document as PDF
doc.SaveAs(output_pdf, FileFormat=17)
# Close the document and the Word application
doc.Close()
word_app.Quit()
xxxxxxxxxx
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
public class DocToPDF {
public static void main(String[] args) {
try {
InputStream templateInputStream = new FileInputStream("D:\\\\Workspace\\\\New\\\\Sample.docx");
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
String outputfilepath = "D:\\\\Workspace\\\\New\\\\Sample.pdf";
FileOutputStream os = new FileOutputStream(outputfilepath);
Docx4J.toPDF(wordMLPackage,os);
os.flush();
os.close();
} catch (Throwable e) {
e.printStackTrace();
}
}
}