Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / MFC

Convert Document File to PDF

2.62/5 (4 votes)
9 Sep 2021CPOL1 min read 9.6K   361  
A simple way to convert an office document to PDF
In this post, you will find a solution to convert document file to PDF without having any Office installed.

Image 1

Introduction

There are several solutions to convert office files into pdf file that use Microsoft Office Suite, but these ones require to have Microsoft Office installed. You can find an approach to accomplish that here.

Background

In this tip, I am presenting a way to convert a document file (office file), doc/xls/ppt/docx/xlsx/pptx and not only, even txt, rtf, xml, html (and so on) into a PDF file. The news here is that this solution doesn't require any Microsoft Office Suite installed, or any other application installed. However, the solution uses LibreOffice as conversion engine. But this application, LibreOffice, could be used without being installed.

Using the Code

I encapsulated this solution into a MFC SDI application that has CView based on CHtmlView in order to display the outcome: the PDF file. The code is pretty simple and straightforward, in fact it uses CreateProcess function to send the conversion command to a LibreOffice executable engine:

C++
STARTUPINFO si = { 0 };
si.cb = sizeof(si);
PROCESS_INFORMATION pi = { 0 };
sCommand.Format(_T("C:\\WINDOWS\\System32\\cmd.exe /c
C:\\LibreOffice\\program\\swriter.exe --convert-to pdf -outdir
c:\\temp\\  c:\\temp\\MyFile.doc"));
::CreateProcess(0, sCommand, 0, 0, TRUE, CREATE_NO_WINDOW, 0, 0, &si, &pi);

Before doing anything, you need to setup a conversion engine from Edit->Set Engine, or else you'll be notified to do that before doing a conversion:

Image 2

As you may have noticed, I setup here a portable version of LibreOffice, and that means there is no need to have any Office or LibreOffice installed. Once you have done that, the application simply uses this path to make the conversion.

After the conversion has been done, the test application automatically loads the pdf file. Of course, your Internet Explorer application should be able to load pdf file in it, or, the pdf file will be opened in your default pdf client.

Image 3

Enjoy it!

History

  • 9th September, 2021: Posted tip

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)