Skip to content

Instantly share code, notes, and snippets.

@jinan-kordab
Created November 3, 2018 10:08
Show Gist options
  • Save jinan-kordab/e40f04b60d4f0ac1270b9b93e15bd733 to your computer and use it in GitHub Desktop.
Save jinan-kordab/e40f04b60d4f0ac1270b9b93e15bd733 to your computer and use it in GitHub Desktop.
Create, customize, and print PDF documents using C#, PdfSharp, and HtmlRenderer
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using PdfSharp.Drawing;
using TheArtOfDev.HtmlRenderer.PdfSharp;
namespace temp01.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
//Create your HTML page that you want to print
StringBuilder HTMLContent = new StringBuilder("<!DOCTYPE html><html lang = \"en\"><head></head><body>Your Table To Print Go here</body></html>");
//Prepare the HTTP response
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + "MyDataReport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Configure page settings
var configurationOptions = new PdfGenerateConfig();
//Page is in Landscape mode, other option is Portrait
configurationOptions.PageOrientation = PdfSharp.PageOrientation.Landscape;
//Set page type as Letter. Other options are A4 ...
configurationOptions.PageSize = PdfSharp.PageSize.Letter;
//This is to fit Chrome Auto Margins when printing.Yours may be different
configurationOptions.MarginBottom = 19;
configurationOptions.MarginLeft = 2;
//The actual PDF generation
var OurPdfPage = PdfGenerator.GeneratePdf(HTMLContent.ToString(), configurationOptions);
//Setting Font for our footer
XFont font = new XFont("Segoe UI,Open Sans, sans-serif, serif", 7);
XBrush brush = XBrushes.Black;
//Loop through our generated PDF pages, one by one
for (int i = 0; i < OurPdfPage.PageCount; i++)
{
//Get each page
PdfSharp.Pdf.PdfPage page = OurPdfPage.Pages[i];
//Create rectangular area that will hold our footer - play with dimensions according to your page'scontent height and width
XRect layoutRectangle = new XRect(0/*X*/, page.Height - (font.Height + 9)/*Y*/, page.Width/*Width*/, (font.Height - 7)/*Height*/);
//Draw the footer on each page
using (XGraphics gfx = XGraphics.FromPdfPage(page))
{
gfx.DrawString(
"Page " + i + " of " + OurPdfPage.PageCount,
font,
brush,
layoutRectangle,
XStringFormats.Center);
}
}
//Prepare to download
var outputstream = new MemoryStream();
OurPdfPage.Save(outputstream);
//Write the PDF file. Browsers will trigger a popup asking to save or open a PDF file.
Response.BinaryWrite(outputstream.ToArray());
//Close the HTTP Response Stream
Response.End();
return View();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment