Reputation: 671
I have a PNG file that is used as a Template, then I use PDFSharp.Drawing to write over the image which in turn produces a Certificate as a PDF, as shown below:
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);
This can open this in my default PDF Viewer (Edge in my case) and I am able to save from there, but when I try to save from the Site and not the PDF viewer I only save the Template and not any of the Text which is written over.
My code to Save the file is here:
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=MyCertificate.pdf");
Response.TransmitFile(Server.MapPath("~/Content/Images/Certificate/MyCertificate.png"));
Response.End();
I'm fairly certain that the reason I am only saving the Template is because I set the Server MapPath to the location of the template, but the finished certificate is never actually saved on our side.
How can I save the PDF (with the text) instead of just the template if it is not saved anywhere before-hand on my side?
Thanks.
Upvotes: 0
Views: 1644
Reputation: 35514
You have to write the PDF to the browser using a MemoryStream
. Adding the PDF name to the header with AppendHeader
does not send it to the browser.
//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();
Upvotes: 1