gpt4 book ai didi

c# - 为什么 MigraDoc 在我的 asp.net 应用程序中生成空白 pdf?

转载 作者:太空宇宙 更新时间:2023-11-03 21:54:29 26 4
gpt4 key购买 nike

我在尝试创建 PDF 时使用了以下代码:

    public static MemoryStream Test()
{
var document = new Document();
document.Info.Title = "Test Report";
document.Info.Subject = "blah";
document.Info.Author = "Me";
//new CoverPageSummarySection().AddToDocument(document, new int[0], 2004);

Style style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style = document.Styles["Heading1"];
style.Font.Name = "Tahoma";
style.Font.Size = 14;
style.Font.Bold = true;
style.Font.Color = Colors.DarkBlue;
style.ParagraphFormat.PageBreakBefore = true;
style.ParagraphFormat.SpaceAfter = 6;

var section = document.AddSection();
var p = section.AddParagraph("test");
p.AddText("Testing 1234");

var renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
renderer.Document = document;
renderer.RenderDocument();

var ms = new MemoryStream();
renderer.PdfDocument.Save(ms, false);
return ms;
}

生成的 pdf 是空白的。我可以查看属性并且 document.Info 字段在我的 PDF 中正确显示,但我在我的页面上看不到任何文本。

我做错了什么?


编辑: 看来这个问题与保存到内存流有关。当我将 renderer.PdfDocument.Save(ms, false); 替换为 renderer.PdfDocument.Save("e:\\test.pdf"); 它会正确保存在 test.pdf.

我将内存流保存到 asp.net 输出的代码是:

        var stream = TestReportGen.Test();

// Set the content headers
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=testReport.pdf");

stream.WriteTo(HttpContext.Current.Response.OutputStream);
stream.Close();

HttpContext.Current.Response.End();

是我发回内存流的方式有问题还是什么?

最佳答案

假设您有一个有效的 MigraDoc 文档,以下内容应该有效:

PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfFontEmbedding.Always);
renderer.Document = document;
renderer.RenderDocument();

// Send PDF to browser
MemoryStream stream = new MemoryStream();
renderer.PdfDocument.Save(stream, false);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", stream.Length.ToString());
Response.BinaryWrite(stream.ToArray());
Response.Flush();
stream.Close();
Response.End();

关于c# - 为什么 MigraDoc 在我的 asp.net 应用程序中生成空白 pdf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12864051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com