这是另一个解决方案:
1)下载SumatraPDF(便携版)- https://www.sumatrapdfreader.org/download-free-pdf-viewer.html
2)创建一个类库工程,将SumatraPDF.exe解压到工程目录根目录下并解封。
3) 在项目属性中,转到资源选项卡并将 exe 添加为文件。
4)将以下类添加到您的库中:
public class SumatraWrapper : IDisposable
{
private readonly FileInfo _tempFileForExe = null;
private readonly FileInfo _exe = null;
public SumatraWrapper()
{
_exe = ExtractExe();
}
public SumatraWrapper(FileInfo tempFileForExe)
: this()
{
_tempFileForExe = tempFileForExe ?? throw new ArgumentNullException(nameof(tempFileForExe));
}
private FileInfo ExtractExe()
{
string tempfile =
_tempFileForExe != null ?
_tempFileForExe.FullName :
Path.GetTempFileName() + ".exe";
FileInfo exe = new FileInfo(tempfile);
byte[] bytes = Properties.Resources.SumatraPDF;
using (FileStream fs = exe.OpenWrite())
{
fs.Write(bytes, 0, bytes.Length);
}
return exe;
}
public bool Print(FileInfo file, string printerName)
{
string arguments = $"-print-to \"{printerName}\" \"{file.FullName}\"";
ProcessStartInfo processStartInfo = new ProcessStartInfo(_exe.FullName, arguments)
{
CreateNoWindow = true
};
using (Process process = Process.Start(processStartInfo))
{
process.WaitForExit();
return process.ExitCode == 0;
}
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
try
{
File.Delete(_exe.FullName);
}
catch
{
}
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~PdfToPrinterWrapper() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
}
5) 享受从您的代码中打印 pdf 文件的乐趣。
像这样使用:
FileInfo file = new FileInfo(@"c:\Sandbox\dummy file.pdf");
SumatraWrapper pdfToPrinter =
new SumatraWrapper();
pdfToPrinter.Print(file, "My Printer");