Reputation: 117
How i can convert word file (.docx & doc
) to .pdf
in c#
without using SaveAs()
or Save()
method ? or without uploading on server?
Upvotes: 7
Views: 27148
Reputation: 9489
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<string>
{
"--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], $"{originalFileName}.pdf");
while (currentCheck <= totalChecks)
{
if (File.Exists(newFilePath))
{
// File conversion was successful
break;
}
Thread.Sleep(500); // LibreOffice doesn't immediately create PDF output once the command is run
}
}
}
}
}
Upvotes: 0
Reputation: 11
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);
}
}
}
Upvotes: 1
Reputation: 101
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();
}
}
Upvotes: 0
Reputation: 145
Aspose.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
Code example:
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");
}
}
}
Upvotes: 6
Reputation: 848
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();
}
}
}
Upvotes: 2
Reputation: 77
Try 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();
}
Upvotes: 7