如何使用iText 7将PDF写到HttpResponseMessage中

问题描述 投票:0回答:1

我正在尝试使用iText 7和iText7.pdfHtml库生成PDF并将其写入HTTP响应。

PDF的HTML内容存储在StringBuilder对象中。

不确定执行此操作的正确过程是什么,因为一旦使用HtmlConverter.ConvertToPdfMemoryStream就关闭了,并且无法访问字节。我收到以下异常:

System.ObjectDisposedException:无法访问关闭的Stream。

HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
StringBuilder htmlText = new StringBuilder();
htmlText.Append("<html><body><h1>Hello World!</h1></body></html>");
using (MemoryStream memoryStream = new MemoryStream())
{
    using (PdfWriter pdfWriter = new PdfWriter(memoryStream))
    {
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        Document document = new Document(pdfDocument);

        string headerText = "my header";
        string footerText = "my footer";

        pdfDocument.AddEventHandler(PdfDocumentEvent.END_PAGE, new HeaderFooterEventHandler(document, headerText, footerText));

        HtmlConverter.ConvertToPdf(htmlText.ToString(), pdfWriter);

        memoryStream.Flush();
        memoryStream.Seek(0, SeekOrigin.Begin);

        byte[] bytes = new byte[memoryStream.Length];
        memoryStream.Read(bytes, 0, (int)memoryStream.Length);

        Stream stream = new MemoryStream(bytes);
        httpResponseMessage.Content = new StreamContent(stream);

        httpResponseMessage.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/pdf");
        httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "sample.pdf"
        };
        httpResponseMessage.StatusCode = HttpStatusCode.OK;
    }//end using pdfwriter
}//end using memory stream

编辑添加了PdfDocumentDocument对象,以操作页眉/页脚和新页面。

c# pdf-generation itext7
1个回答
0
投票

利用您拥有MemoryStream的事实并进行替换

    memoryStream.Flush();
    memoryStream.Seek(0, SeekOrigin.Begin);

    byte[] bytes = new byte[memoryStream.Length];
    memoryStream.Read(bytes, 0, (int)memoryStream.Length);

作者

byte[] bytes = memoryStream.ToArray();

该方法也可以在封闭的内存流中使用。

© www.soinside.com 2019 - 2024. All rights reserved.