【发布时间】:2013-01-17 23:11:26
【问题描述】:
我需要打印一个我已更改的 pdf 文档,但不将其保存为新的 pdf 文档。下面的代码可以正常工作。但是,我想以完全不同的方式做到这一点,并且我同时有大脑滞后并且看不到解决方案。
我的代码示例
byte[] result;
using (MemoryStream ms = new MemoryStream())
{
PdfReader pdfReader = new PdfReader("c:\\templatePdf.pdf");
PdfStamper pdfStamper = new PdfStamper(pdfReader, ms);
/* abbreviated but here I alter the template pdf */
pdfStamper.FormFlattening = true;
pdfStamper.Close();
result = ms.GetBuffer();
}
/* Instead of saving a new file I would rather like to print
the altered template pdf in memory and then discard it */
using (FileStream fs = File.Create("C:\\Test.pdf"))
{
fs.Write(result, 0, (int)result.Length);
}
Process process = new Process();
process.StartInfo.FileName = "C:\\Test.pdf";
process.StartInfo.Verb = "printto";
process.StartInfo.Arguments = "\"" + ppr_PrinterDropDown.Text + "\"";
process.Start();
File.Delete("C:\\Test.pdf");
【问题讨论】:
-
你应该使用
result = ms.GetBuffer()- 你应该使用ToArray()。否则你会有一堆尾随空值。此外,使用File.WriteBytes或仅使用MemoryStream.WriteTo让生活更简单。 -
感谢您的评论@JonSkeet,但我将如何在进程中处理它而进程需要读取文件名? (我的意思是这样我可以打印 pdf);)
-
这并不是一个答案——它只是围绕现有代码的一个旁白。根据 Marc 的回答,我怀疑您仍然需要使用文件。
-
是的,你们俩可能都是对的。感谢您的 cmets :)
-
我一直在研究类似的东西(更新 pdf 表单然后打印,而不将中间文件保存到磁盘)。你有没有想过没有磁盘写入的打印方法?似乎答案会导致作为一种选择,但我想我会问。
标签: c# pdf itextsharp