Converting docx template to pdf

Viewed 59

I'm trying to programmatically populate a template (.docx file) and save it as a PDF. Is there a free library to do this? Or possibly another format to use for the template?

Would prefer not to pay to use interop methods, online services, or pay tons of money if possible.

I could use RDLC but I'd prefer to be able to modify the template with something like Word.

Using asp.net core 6.

2 Answers

DocX has specifically MS Office Objects thus traditionally uses features like OLE, MS WordArt etc.

Hence the No 1 quality convert MS Word DocX to MS PDF is export from Word.

The simpler native windows method is use WordPad print probably pre processed via tar to inject the template forms data xml into the zip.docx.

Write /pt MyXML.Zip.docx "Microsoft Print to PDF" "Microsoft Print to PDF" output.pdf

enter image description here

see https://github.com/GitHubRulesOK/MyNotes/raw/master/AppNotes/Doc2PDF.cmd

Since DocX is similar is some areas and features to Open Office Documents, then either Open office or Libre Office save as PDF is the second best option.

Libre/Open Office is cross platform and can be driven via command line, or Basic for office applications, thus an ideal candidate for conversions.

The list of command line options for Libre Office is currently at https://help.libreoffice.org/latest/en-US/text/shared/guide/start_parameters.html

To call writer you simply invoke along the lines of

 soffice --headless --convert-to pdf --outdir /folder/ /path/to/input.docx 

using options as per https://stackoverflow.com/a/70735498/10802527

You could try to use Microsoft.interop.Word or you could try to make a tests with the Open-XML-SDK

I tried to make a test with the Microsoft.interop.Word in the Asp.Net Core 6 project and I could see that it works fine.

After creating the project, you need to right-click the Dependencies -> Add COM Reference and add a reference to the Microsoft Word 16.0 Object library.

enter image description here

Below is my test code which created the Word file.

using Word=Microsoft.Office.Interop.Word;

object missing = System.Reflection.Missing.Value;
            var wordApp = new Word.Application();
            wordApp.Visible = true;
            Microsoft.Office.Interop.Word.Document document= wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            object filename = @"C:\Users\Administrator\Desktop\temp1.docx";
            document.SaveAs2(ref filename);
            document.Close(ref missing, ref missing, ref missing);
            document = null;
            wordApp.Quit(ref missing, ref missing, ref missing);
            wordApp = null;

Further, you could modify it as per your requirements.

Below are some helpful links:

  1. To add a Word document
  2. How to Create Word Document Using C#
  3. How to automate Microsoft Word to create a new document by using Visual C#
Related