0

I have a Docx Word Document and I am trying to convert it to PDF using a virtual PDF printer such as PDFCreator or similars. I want to do the same as when you open a document in Word and then you print it using an available virtual PDF printer installed on the system but in my case I am interested in doing it from C# programatically and silently (without showing user any popup window).

I am not interested in using Word Interop (Office Automation).

Could anyone provide me some example?

Willy
  • 9,848
  • 22
  • 141
  • 284

2 Answers2

1

For this purpose I use an external dll that is simple to use.

( I took the code from : https://sautinsoft.com/products/pdf-metamorphosis/examples/convert-docx-to-pdf-in-memory-csharp-vb-net.php )

SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();
string docxPath = @"..\..\example.docx";
string pdfPath = Path.ChangeExtension(docxPath, ".pdf");
byte[] docx = File.ReadAllBytes(docxPath);
    
// 2. Convert DOCX to PDF in memory
byte[] pdf = p.DocxToPdfConvertByte(docx);
    
if (pdf != null)
{
    // 3. Save the PDF document to a file for a viewing purpose.
    File.WriteAllBytes(pdfPath, pdf);
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Sersis
  • 11
  • 1
0

You can check out the leadtools Virtual Printer c# sdk.

This will allow you to create a custom virtual printer and give events that you control to do a variety of different things, including saving it out to a PDF silently.

There is a tutorial here that you can follow to test it out with a free eval: Print to File Using the Virtual Printer Driver - Console C#

The relevant pieces of the is highlighted below:

The Emf Event will fire for each page of a print job. The Job Event will fire twice: the first time when the job begins, and a second time when the job ends.

static void LeadPrinter_EmfEvent(object sender, EmfEventArgs e) 
{ 
    Metafile metaFile = new Metafile(e.Stream); 
 
    DocumentWriterEmfPage documentPage = new DocumentWriterEmfPage 
    { 
        EmfHandle = metaFile.GetHenhmetafile() 
    }; 
    DocumentWriter.AddPage(documentPage); 
} 
 
static void LeadPrinter_JobEvent(object sender, JobEventArgs e) 
{ 
    string printerName = e.PrinterName; 
    int jobID = e.JobID; 
 
    if (e.JobEventState == EventState.JobStart) 
    { 
        OutputFile = Path.Combine(@"C:\Temp", Path.ChangeExtension(Path.GetRandomFileName(), "pdf")); 
        DocumentWriter.BeginDocument(OutputFile, DocumentFormat.Pdf); 
 
        Console.WriteLine($"Job {jobID} for {printerName} was started"); 
    } 
    else if (e.JobEventState == EventState.JobEnd) 
    { 
        DocumentWriter.EndDocument(); 
 
        Console.WriteLine($"Job {jobID} for {printerName} was ended. PDF saved to {OutputFile}"); 
    } 
} 

Please note that I am an employee of this company

hcham1
  • 1,799
  • 2
  • 16
  • 27