问题描述
我正在尝试使用 Microsoft Print to PDF 打印机将 XPS 转换为 PDF。
我尝试使用 GhostReader 通过命令行转换我的 XPS 文件,还尝试使用 PdfSharp.Xps。这两个都太慢了,一个 10 页的 XPS 文件需要超过 30 秒。现在我的问题是,当我使用 Microsoft 打印到 PDF 时,是否可以设置用于打印的输入和输出文件/路径
string fileGuid = Guid.NewGuid().ToString();
string xpsFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(),$"{fileGuid}.Print.xps");
string pdfFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(),$"{fileGuid}.Print.pdf");
PrintDocument doc = new PrintDocument()
{
DocumentName = xpsFile,PrinterSettings = new PrinterSettings()
{
PrinterName = "Microsoft Print to PDF",PrintToFile = true,PrintFileName = pdfFile,}
};
doc.Print();
这是我尝试过的。但这会创建一个我无法使用的空 .PDF 文件
解决方法
您可以查看LEADTOOLS SDK(免责声明:我是该供应商的员工),它实际上支持在 C# 中加载和保存 XPS 文件,因此您无需使用打印机进行转换,您可以只需直接在您的应用程序中执行此操作:https://www.leadtools.com/sdk/formats#document
因此,您可以使用该工具包简单地加载 XPS,并使用以下代码和 nuget 包轻松将其另存为 PDF:
Install-Package Leadtools.Document.Sdk -Version 21.0.0.2
using (DocumentConverter documentConverter = new DocumentConverter())
{
documentConverter.SetDocumentWriterInstance(new DocumentWriter();
foreach (var filename in inputFiles)
{
var jobData = new DocumentConverterJobData();
jobData.InputDocumentFileName = "input.xps";
jobData.DocumentFormat = DocumentFormat.Pdf;
jobData.OutputDocumentFileName = "output.pdf");
var job = documentConverter.Jobs.CreateJob(jobData);
documentConverter.Jobs.RunJobAsync(job);
}
}
以下是有关如何实现此目标的完整教程:https://test.leadtools.com/help/sdk/v21/tutorials/documents/cross-platform/dotnet-core/convert-files-with-the-document-converter.html
如果您更愿意使用打印机来执行此功能,还有支持 XPS -> PDF 转换的虚拟打印机驱动程序: https://www.leadtools.com/help/sdk/v21/tutorials/virtual-printer/windows/dotnet/print-to-file-using-the-virtual-printer-driver.html