我正在尝试使用C#代码打印pdf文件。当我运行代码时,我得到显示“正在打印”但没有可用的pdf或xps输出的打印对话框。我是从控制台应用程序而不是gui执行此操作的。这是我当前的代码:
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
public class PrintFile {
public static void printFilePath(String filePath, String printer) {
try {
var streamToPrint = new StreamReader(filePath);
try {
PrintDocument pd = new PrintDocument();
pd.PrinterSettings.PrinterName = printer;
// set landscape to false
pd.DefaultPageSettings.Landscape = false;
// set margins to zero
Margins margins = new Margins(0,0,0,0);
pd.DefaultPageSettings.Margins = margins;
// print
pd.Print();
} catch (Exception ex) {
Console.WriteLine(ex);
}
finally {
Console.WriteLine("closing");
streamToPrint.Close();
}
} catch (Exception ex) {
Console.WriteLine(ex);
}
}
public static void Main(string[] args) {
String filePath = "C:\\Projects\\C\\girl.pdf";
String printer = "Microsoft Print to PDF";
printFilePath(filePath, printer);
}
}
感谢您的帮助。我还要设置份数,纸张尺寸(A4,e.t.c)以及黑白/彩色。谢谢。
更新:
根据下面的评论,我更新了代码。仍然无法获得它来打印确切的文档,但是至少它似乎可以打印一些东西。真的很感谢任何进一步的建设性反馈
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
public class PrintFile {
private static Font printFont;
private static StreamReader streamToPrint;
// The PrintPage event is raised for each page to be printed.
private static void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics);
// Print each line of the file.
while (count < linesPerPage &&
((line = streamToPrint.ReadLine()) != null))
{
yPos = topMargin + (count *
printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
public static void printFilePath(String filePath, String printer) {
try {
streamToPrint = new StreamReader(filePath);
try {
printFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
pd.PrinterSettings.PrinterName = printer;
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
// set landscape to false
pd.DefaultPageSettings.Landscape = false;
// set margins to zero
Margins margins = new Margins(0,0,0,0);
pd.DefaultPageSettings.Margins = margins;
// print
pd.Print();
} catch (Exception ex) {
Console.WriteLine(ex);
}
finally {
Console.WriteLine("closing");
streamToPrint.Close();
}
} catch (Exception ex) {
Console.WriteLine(ex);
}
}
public static void Main(string[] args) {
String filePath = "C:\\Projects\\C\\nnkl.pdf";
String printer = "Microsoft Print to PDF";
printFilePath(filePath, printer);
}
}