要下载 pdf 文件,请使用 iTextSharp 尝试此解决方案:
ITextSharp HTML to PDF?
如果你想直接保存到文件中,除了一个替换
private MemoryStream createPDF(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
// step 1: creation of a document-object
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
// step 2:
// we create a writer that listens to the document
// and directs a XML-stream to a file
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c:\\my.pdf", FileMode.Create));
// step 3: we create a worker parse the document
HTMLWorker worker = new HTMLWorker(document);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
return msOutput;
}
PDF 设置完成后,尝试使用 ghostscript 打印一页:
Print existing PDF (or other files) in C#
如果您启动进程的 shell 执行,您可以使用命令行参数:
gsprint "filename.pdf" -from 1 - to 1
或者,WebBrowser 可以只打印整页:http://msdn.microsoft.com/en-us/library/b0wes9a3.aspx
我找不到任何引用 WebBrowser 本身可以在没有打印对话框的情况下打印“从页面 X 到 Y”的内容。
由于我面临类似的问题,这里有一个替代解决方案:
这个开源项目将 HTML 文档转换为类似于 iTextSharp (http://code.google.com/p/wkhtmltopdf/) 的 PDF 文档。我们最终没有使用 iTextSharp,因为我们想要打印的网站的布局方式存在一些格式问题。我们发送命令行参数以将使用 webclient 下载的 html 转换为 pdf 文件。
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultNetworkCredentials;
string htmlText = wc.DownloadString("http://websitehere.com);
然后,转成pdf后,就可以简单的打印文件了:
Process p = new Process();
p.StartInfo.FileName = string.Format("{0}.pdf", fileLocation);
p.StartInfo.Verb = "Print";
p.Start();
p.WaitForExit();
(对于C#的道歉,我比VB.NET更熟悉它,虽然它应该是一个简单的转换)