保存从代码创建的 PDF 文件

Save PDF file that is created from code

我有一个用作模板的 PNG 文件,然后我使用 PDFSharp.Drawing 覆盖图像,然后生成 PDF 格式的证书,如下所示:

PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PDFsharp";

// Create an empty page 
PdfPage page = document.AddPage();
page.Width = 419;
page.Height = 595;
page.Orientation = PdfSharp.PageOrientation.Landscape;

// Get an XGraphics object for drawing 
XGraphics gfx = XGraphics.FromPdfPage(page);

// Draw background
gfx.DrawImage(XImage.FromFile(Server.MapPath("~/Content/Images/Certificate/MyCertificate.png")), 0, 0, 595, 419);

// Create fonts
XFont font = new XFont("Verdana", 20, XFontStyle.Regular);

// Draw the text and align on page.
gfx.DrawString("Name", font, XBrushes.Black, new XRect(0, 77, page.Width, 157), XStringFormats.Center);

这可以在我的默认 PDF 查看器(在我的例子中是 Edge)中打开它,我可以从那里保存,但是当我尝试从站点而不是 PDF 查看器保存时,我只保存了模板而不是任何被覆盖的文本。

我保存文件的代码在这里:

Response.ContentType = "application/pdf";

Response.AppendHeader("Content-Disposition", "attachment; filename=MyCertificate.pdf");

Response.TransmitFile(Server.MapPath("~/Content/Images/Certificate/MyCertificate.png"));

Response.End();

我很确定我只保存模板的原因是因为我将 Server MapPath 设置为模板的位置,但完成的证书从未真正保存在我们这边。

如果事先没有保存在我这边的任何地方,我如何保存 PDF(带有文本)而不仅仅是模板?

谢谢。

您必须使用 MemoryStream 将 PDF 写入浏览器。使用 AppendHeader 将 PDF 名称添加到 header 不会将其发送到浏览器。

//create an empty byte array
byte[] bin;

//'using' ensures the MemoryStream will be disposed correctly
using (MemoryStream stream = new MemoryStream())
{
    //save the pdf to the stream
    document.Save(stream, false);

    //fill the byte array with the pdf bytes from stream
    bin = stream.ToArray();
}

//clear the buffer stream
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;

//set the correct ContentType
Response.ContentType = "application/pdf";

//set the correct length of the string being send
Response.AddHeader("content-length", bin.Length.ToString());

//set the filename for the pdf
Response.AddHeader("content-disposition", "attachment; filename=\"MyCertificate.pdf\"");

//send the byte array to the browser
Response.OutputStream.Write(bin, 0, bin.Length);

//cleanup
Response.Flush();
Response.Close();