2016-10-18 13 views
0

テンプレートとして使用されるPNGファイルがある場合は、次にPDFSharp.Drawingを使用してイメージを上書きし、次に証明書をPDFとして生成します。コードから作成された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(); 

私は、テンプレートの場所にサーバーMapPathのを設定するので、私は唯一のテンプレートを保存していた理由であることをかなり確信しているが、完成した証明書が実際に私たちの側に保存されることはありません。

私の側で手前に保存されていない場合は、テンプレートだけでなくPDFをテキストで保存するにはどうすればよいですか?

ありがとうございました。

+0

なぜあなたは 'png'をクライアントに送りますか? – Xaqron

答えて

1

MemoryStreamを使用してPDFをブラウザに書き込む必要があります。 AppendHeaderを使用してPDF名をヘッダに追加しても、ブラウザには送信されません。

//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(); 
+0

それは素晴らしい、ありがとう! –

関連する問題