![](/img/trans.png)
[英]Adding text to existing multipage PDF document in memorystream using iTextSharp
[英]Loading an iTextSharp Document into MemoryStream
我正在開發一個ASP.NET應用程序,在該應用程序中,我必須基於在頁面上動態創建的表發送PDF作為電子郵件的附件。 因此,我有一個將PDF創建為iTextSharp文檔並返回它的函數。 如果我只是嘗試保存此文檔,則可以正常工作,但是我很難將其設置為Stream。 我已經嘗試過幾件事,但是總會遇到困難。
我試圖對其進行序列化,但是似乎Document無法序列化。 然后,我嘗試使用PdfCopy,但我不知道如何針對具體問題來使用它。
現在的代碼是這樣的:
//Table,string,string,Stream
//This document returns fine
Document document = Utils.GeneratePDF(table, lastBook, lastDate, Response.OutputStream);
using (MemoryStream ms = new MemoryStream())
{
PdfCopy copy = new PdfCopy(document, ms);
//Need something here to copy from one to another! OR to make document as Stream
ms.Position = 0;
//Email, Subject, Stream
Utils.SendMail(email, lastBook + " - " + lastDate, ms);
}
盡量避免傳遞本地iTextSharp對象。 傳遞流,文件或字節。 我現在沒有IDE,但您應該可以執行以下操作:
byte[] Bytes;
using(MemoryStream ms = new MemoryStream()){
Utils.GeneratePDF(table, lastBook, lastDate, ms);
Bytes = ms.ToArray();
}
然后,您可以將Utils.SendMail()
更改為接受字節數組,也可以將其包裝在另一個流中 。
編輯
您也許還可以在代碼中執行以下操作:
using(MemoryStream ms = new MemoryStream()){
Utils.GeneratePDF(table, lastBook, lastDate, ms);
ms.Position = 0;
Utils.SendMail(email, lastBook + " - " + lastDate, ms);
}
我過去通過執行以下操作來做到這一點:
using (Document doc = new Document())
{
MemoryStream msPDFData = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, msPDFData);
doc.Open();
doc.Add(new Paragraph("I'm a pdf!");
}
如果您需要訪問原始數據,也可以執行
byte[] pdfData = msPDFData.ToArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.