簡體   English   中英

從MemoryStream打印pdf文檔

[英]Print pdf document from MemoryStream

我需要打印已經更改過的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");

如果您使用的是基於文件的API,那么您將很難在沒有文件的情況下進行操作。 也許可以設置一個命名管道服務器,但是坦率地說,這是一個很大的麻煩。 但是,我很想四處尋找具有打印支持的完全托管的PDF庫。 但是最終……文件系統確實在危害什么? 可能不是很多。 不過,我可能會建議進行一些調整:

  1. 使用臨時區域( Path.GetTempPath() ),而不是C:\\Test
  2. 等待過程完成,然后再刪除文件

首先,我們需要寫入內存流,然后借助內存流方法“ WriteTo”,我們可以寫入頁面的響應,如以下代碼所示。

   MemoryStream filecontent = null;
   filecontent =//CommonUtility.ExportToPdf(inputXMLtoXSLT);(This will be your MemeoryStream Content)
   Response.ContentType = "image/pdf";
   string headerValue = string.Format("attachment; filename={0}", formName.ToUpper() + ".pdf");
   Response.AppendHeader("Content-Disposition", headerValue);

   filecontent.WriteTo(Response.OutputStream);

   Response.End();

FormName是給定的文件名,此代碼將通過調用PopUp使生成的PDF文件可下載。

這很容易。 困難的部分是獲得有關打印狀態完成和總頁數的有用信息。

var pq = LocalPrintServer.GetDefaultPrintQueue();
var theJob = pq.AddJob();
try{
    using(var js = theJob.JobStream){
        var buffer = File.ReadAllBytes("yourPathToPdf");
        js.Write(buffer,0,buffer.Length);
    }
    var done=false;
    while(!done)
    {
        pq.Refresh();
        theJob.Refresh();
        done = theJob.IsCompleted || theJob.IsDeleted || theJob.IsPrinted;
    }
}
catch(Exception ex){
    //handle this
}
finally{
    theJob?.Dispose();
    pq?.Dispose();
}

當然,這是假設您的打印機具有本機PDF支持。 否則,您將必須自己在客戶端上執行渲染工作,而不是將其作為原始流發送。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM