How i can convert word file ( .docx & doc ) to .pdf in c# without using SaveAs() or Save() method ? or without uploading on server?
509 4 4 silver badges 17 17 bronze badges asked Jul 18, 2016 at 7:29 107 1 1 gold badge 1 1 silver badge 6 6 bronze badges Possible duplicate of How to convert .docx to .pdf in C# Commented Jul 18, 2016 at 7:31Try this, it works for me:
using Microsoft.Office.Interop.Word; var appWord = new Application(); if (appWord.Documents != null) < //yourDoc is your word document var wordDocument = appWord.Documents.Open(yourDoc); string pdfDocName = "pdfDocument.pdf"; if (wordDocument != null) < wordDocument.ExportAsFixedFormat(pdfDocName, WdExportFormat.wdExportFormatPDF); wordDocument.Close(); >appWord.Quit(); >
154k 81 81 gold badges 305 305 silver badges 446 446 bronze badges
answered Jul 18, 2016 at 8:40
67 1 1 silver badge 3 3 bronze badges
how i can download this converted file ?
Commented Jul 21, 2016 at 14:15
After this step it will be saved as pdfDocument.pdf, you will have to find it in your files.
Commented Jul 21, 2016 at 15:19
in my website i want to put an option for to convert .doc of .doxc to .pdf now how user will download this file as i dn't want to save use files on server?
Commented Jul 21, 2016 at 15:38It sounds like this is unsupported in a server environment. The recommended approach is to use OpenXML but there is no apparent way to use OpenXML to save as a PDF which is how I stumbled upon this question.
Commented Mar 7, 2019 at 15:26@user875234 not just unsupported, it's simply a very bad idea - you need a license for every browser user and every request is going to start a new instance of Word. Even if you take care to kill instances by using a using block, a busy site may end up starting 10 or 20 Word instances at the same time
Commented Sep 1, 2020 at 10:14Aspose.Words is really good solution for this purpose if you can buy the license. The free version adds warning messages to the output PDF.
If you're looking for something free, I have used FreeSpire.Doc, the free version has the following limits:
Free version is limited to 500 paragraphs and 25 tables. This limitation is enforced during reading or writing files. When converting word documents to PDF and XPS files, you can only get the first 3 page of PDF file. Upgrade to Commercial Edition of Spire.Doc
MS Office, Office.Interop or Office automations are not required.
Install via NuGet:
Install-Package FreeSpire.Doc -Version 7.11.0
using System; using Spire.Doc; using Spire.Doc.Documents; namespace DoctoPDF < class toPDF < static void Main(string[] args) < //Load Document Document document = new Document(); document.LoadFromFile(@"E:\work\documents\TestSample.docx"); //Convert Word to PDF document.SaveToFile("toPDF.PDF", FileFormat.PDF); //Launch Document System.Diagnostics.Process.Start("toPDF.PDF"); >> >
answered May 25, 2020 at 21:18
145 1 1 silver badge 8 8 bronze badges
Try this, no extra compiler configuration needed if MS Office Word is installed on your computer:
using System; using System.IO; using System.Reflection; namespace KUtil < public class Word2PDF < static void Main(string[] args) < var word = Type.GetTypeFromProgID("word.application"); dynamic app = Activator.CreateInstance(word); if (args.Length < 1) < return; >var path = args[0]; var outPath = Path.ChangeExtension(path, "pdf"); dynamic doc = app.Documents.Open(path); doc.ExportAsFixedFormat(outPath, ExportFormat:17/*pdf*/); doc.Close(0/*DoNotSaveChanges*/); app.Quit(); > > >
answered May 10, 2020 at 5:53
wangkaibule wangkaibule
848 1 1 gold badge 9 9 silver badges 21 21 bronze badges
Try this. It‘s the most useful and simple method in my opinion. You can easily accomplish this task by following just three simple steps with the help of Spire.Doc for .NET.
To view the full technical blog post follow this link.
using Spire.Doc; namespace ToPDF < class Program < static void Main(string[] args) < //Create a Document object Document document = new Document(); //Load a sample Word document document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx"); //Save the document to PDF document.SaveToFile("ToPDF.pdf", FileFormat.PDF); >> >
1,490 6 6 silver badges 21 21 bronze badges
answered Jun 8, 2023 at 6:36
Gail Thorne Gail Thorne
11 2 2 bronze badges
Based on wangkaibule's answer, PDF conversion with heading bookmarks. It also works under .NET 7 (similar to the linked post).
public static void Convert(string inputFileName, string outputFileName) < // Microsoft.Office.Interop.Word.WdSaveFormat enum const int wdFormatPDF = 17; // Microsoft.Office.Interop.Word.WdExportCreateBookmarks enum const int wdExportCreateHeadingBookmarks = 1; // Microsoft.Office.Interop.Word.WdSaveOptions enum const int wdDoNotSaveChanges = 0; var word = Type.GetTypeFromProgID("word.application"); if (word == null) < throw new ArgumentException("Microsoft Word is not installed on the system."); >dynamic app = Activator.CreateInstance(word); try < dynamic doc = app.Documents.Open(inputFileName); doc.ExportAsFixedFormat(outputFileName, ExportFormat: wdFormatPDF, CreateBookmarks: wdExportCreateHeadingBookmarks); doc.Close(wdDoNotSaveChanges); >finally < app.Quit(); >>
answered Apr 6, 2023 at 14:30
91 1 1 silver badge 3 3 bronze badges
I haven't yet seen an example using LibreOffice. All that's needed is the portable executable and you can do this easily in C# in NET Core. I've got a link to a working NET Core app in this writeup I wrote about solving this problem with LibreOffice.
using System.Diagnostics; namespace ConvertDOCXToPDF < internal class Program < static void Main(string[] args) < // Create LibreOfficeWriter CLI process var commandArgs = new List< "--convert-to", //a flag that will be followed by the file type we want to convert to "pdf:writer_pdf_Export", // the [output file type]:[OutputFilterName] we are requesting the output to be; more details are here (https://help.libreoffice.org/latest/en-US/text/shared/guide/convertfilters.html) "C:\\Users\\zachary\\Downloads\\Letter.docx", // input file "--norestore", // disables restart and file recovery after a system crash "--headless", // allows using the application without user interface "--outdir", // a flag that will be followed by the output directory where we want our new pdf file to be created "C:\\Users\\zachary\\Downloads" // output directory >; // The path to LibreOfficeWriterPortable.exe ProcessStartInfo processStartInfo = new ProcessStartInfo("C:\\Users\\zachary\\Downloads\\LibreOfficePortablePrevious\\LibreOfficeWriterPortable.exe"); foreach (string arg in commandArgs) processStartInfo.ArgumentList.Add(arg); Process process = new Process < StartInfo = processStartInfo >; // Only 1 instance of LibreOfficeWriter can be running at a given time Process[] existingProcesses = Process.GetProcessesByName("soffice"); while (existingProcesses.Length > 0) < Thread.Sleep(1000); existingProcesses = Process.GetProcessesByName("soffice"); >// Start the process process.Start(); process.WaitForExit(); // Check for failed exit code. if (process.ExitCode != 0) throw new Exception("Failed to convert file"); else < int totalChecks = 10; int currentCheck = 1; string originalFileName = Path.GetFileNameWithoutExtension(commandArgs[2]); string newFilePath = Path.Combine(commandArgs[6], $".pdf"); while (currentCheck Thread.Sleep(500); // LibreOffice doesn't immediately create PDF output once the command is run > > > > >