我正在使用ITextSharp生成pdf,我必须使用MemoryStream在内存中生成pdf(因为我没有物理保存文件)。我已经生成了流,但我不了解如何在内存中生成pdf。 这就是我生成Stream的方式
private static byte[] GetFileStream()
{
var stream = new MemoryStream();
Document document = new Document(PageSize.A4, 1f, 1f, 1f, 1f);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Open();
try
{
StringBuilder sb= new StringBuilder();
sb.Append("<table class=\"table\">");
sb.Append("<thead>");
sb.Append("<tr>");
sb.Append(" <th> Crime Category </th>");
sb.Append(" <th>Date</th>");
sb.Append(" <th>City</th>");
sb.Append(" <th>Description</th>");
sb.Append(" <th>Option(s)</th>");
sb.Append(" </tr>");
sb.Append(" </thead>");
sb.Append(" <tbody>");
sb.Append(" <tr><td>This is a test</td><td>2</td><td>3</td><td>4</td><td>5</td><tr/>");
sb.Append(" </tbody>");
sb.Append(" </table>");
List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(misdem.ToString()), null);
for (int k = 0; k < htmlarraylist.Count; k++)
{
document.Add((IElement)htmlarraylist[k]);
}
}
catch (Exception ex)
{ }
finally
{
document.Close();
}
return stream.GetBuffer();
}
byte[] pdfByteData = GetFileStream();
var ms = new MemoryStream(pdfByteData);
我尝试使用此功能,但抛出异常
没有预料到“令牌”。
using (PdfSharp.Pdf.PdfDocument inputDocument = PdfSharp.Pdf.IO.PdfReader.Open(ms, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Import))
{
int count = inputDocument.PageCount;
for (int idx = 0; idx < count; idx++)
{
PdfSharp.Pdf.PdfPage page1 = inputDocument.PageCount > idx ? inputDocument.Pages[idx] : new PdfSharp.Pdf.PdfPage();
// outputDocument.AddPage(page1);
}
}
答案 0 :(得分:1)
4年后......
我意识到你在
中犯了错误sb.Append(" <tr><td>This is a test</td><td>2</td><td>3</td><td>4</td><td>5</td><tr/>");
<tr/>
应该是</tr>
答案 1 :(得分:0)
尝试做:
ms.Seek(0, SeekOrigin.Begin);
创建MemoryStream
编辑:
同时更改返回数据的方式,我不确定GetBuffer
是否符合预期。请改为尝试(目前您有return stream.GetBuffer();
)
stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
byte[] data = new byte[stream.Length];
stream.Read(data, 0, (int)stream.Length);
return data;