65.9K
CodeProject is changing. Read more.
Home

Convert Document File to PDF

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.62/5 (4 votes)

Sep 9, 2021

CPOL

1 min read

viewsIcon

9643

downloadIcon

361

A simple way to convert an office document to PDF

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:

    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:

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.

Enjoy it!

History

  • 9th September, 2021: Posted tip
Convert Document File to PDF - CodeProject