17

Now we are using OpenXML to read data from database and generate doc. But the final requirement is to be a pdf. So I want to know how to convert .docx to pdf in C#. Could anyone for help? Or provide some information.

user2771704
  • 5,994
  • 6
  • 37
  • 38
Robin Sun
  • 1,352
  • 3
  • 20
  • 45
  • I use Aspose.Words to do this. It's a pure .NET library and has pretty decent rendering compatibility. Office Automation might work but is slow but isn't usable in a fully automated environment as it can pop up random windows asking for input. – Cory Nelson Oct 24 '13 at 08:02
  • My favourite solution is to generate an HTML file and let the user print to whatever format they like. Advantages a) no special software needed and b) the printing code is done for you. Obviously, we can help the requirements we are given but the HTML suggestion often goes over well with management. – Gusdor Oct 24 '13 at 08:09
  • If final requirement is pdf then why creating docx ? Can't you directly read database values for creating pdf ? – Software Engineer Oct 24 '13 at 08:11
  • I use GemBox.Document and its [conversion](https://www.gemboxsoftware.com/document/examples/c-sharp-convert-word-html-to-pdf/304) code (Load + Save). Also, regarding generating doc from database, you could check the [mail merge](https://www.gemboxsoftware.com/document/examples/c-sharp-vb-net-mail-merge-word/901) code that does this with ease. – Hazel Patton Dec 02 '19 at 12:53

1 Answers1

15

You can check solutions in this link: http://www.codeproject.com/Questions/346784/How-to-convert-word-document-to-pdf-in-Csharp

I recommend using this among solutions as first:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Word;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
        wordDocument = appWord.Documents.Open(@"D:\desktop\xxxxxx.docx");
        wordDocument.ExportAsFixedFormat(@"D:\desktop\DocTo.pdf", WdExportFormat.wdExportFormatPDF);
    }

    public Microsoft.Office.Interop.Word.Document wordDocument { get; set; }
}
Demir
  • 1,787
  • 1
  • 29
  • 42
  • 8
    Works certainly well, but requires to have Word installed to go. – AFract Jun 30 '14 at 12:20
  • 5
    Although this does work, Microsoft does not recommend having this sit on the servers. Also as AFract said it requires MS office to be installed on the computer which requires extra licensing. – SpaceApple Sep 28 '16 at 07:58
  • 2
    I've seen this sort of thing ruin production servers. It's generally a bad idea due to memory leaks and different threading models. – Mark Fitzpatrick May 02 '18 at 16:33