我有一个 Docx Word 文档,我正在尝试使用 PDFCreator 等虚拟 PDF 打印机将其转换为 PDF。我想做与在 Word 中打开文档然后使用系统上安装的可用虚拟 PDF 打印机打印它时相同的操作,但在我的情况下,我有兴趣从 C# 以编程方式和静默方式执行此操作(不向用户显示任何弹出窗口窗户)。
我对使用 Word Interop(办公自动化)不感兴趣。
谁能给我一些例子?
我有一个 Docx Word 文档,我正在尝试使用 PDFCreator 等虚拟 PDF 打印机将其转换为 PDF。我想做与在 Word 中打开文档然后使用系统上安装的可用虚拟 PDF 打印机打印它时相同的操作,但在我的情况下,我有兴趣从 C# 以编程方式和静默方式执行此操作(不向用户显示任何弹出窗口窗户)。
我对使用 Word Interop(办公自动化)不感兴趣。
谁能给我一些例子?
为此,我使用了一个易于使用的外部 dll。
(我的代码来自: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);
}
您可以查看leadtools Virtual Printer c# sdk。
这将允许您创建自定义虚拟打印机并提供您控制的事件以执行各种不同的操作,包括以静默方式将其保存为 PDF。
这里有一个教程,您可以按照该教程使用免费 eval 对其进行测试: 使用虚拟打印机驱动程序打印到文件 - 控制台 C#
相关部分突出显示如下:
Emf 事件将为打印作业的每一页触发。Job Event 将触发两次:第一次是在作业开始时,第二次是在作业结束时。
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}");
}
}
请注意,我是这家公司的员工