Skip to content

Instantly share code, notes, and snippets.

@agrigg
Last active April 12, 2022 13:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save agrigg/5360230 to your computer and use it in GitHub Desktop.
Save agrigg/5360230 to your computer and use it in GitHub Desktop.
ASP.NET MVC example of using ABCpdf to convert HTML to PDF
public static byte[] PDFForHtml(string html)
{
// Create ABCpdf Doc object
var doc = new Doc();
// Add html to Doc
int theID = doc.AddImageHtml(html);
// Loop through document to create multi-page PDF
while (true)
{
if (!doc.Chainable(theID))
break;
doc.Page = doc.AddPage();
theID = doc.AddImageToChain(theID);
}
// Flatten the PDF
for (int i = 1; i <= doc.PageCount; i++)
{
doc.PageNumber = i;
doc.Flatten();
}
// Get PDF as byte array. Couls also use .Save() to save to disk
var pdfbytes = doc.GetData();
doc.Clear();
return pdfbytes;
}
public static string RenderViewToString(Controller controller, string viewName, object model, string masterName)
{
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, masterName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
public ActionResult Projections(ProjectionsReportViewModel model)
{
// Return view if there is an error
if (!ModelState.IsValid)
{
return View(model);
}
// If user has clicked the export button
if (model.Export)
{
// Render view output to string
var report = RenderViewToString(this, "Projections", model, "_Print");
// Convert string to PDF using ABCpdf
var pdfbytes = PDFForHtml(report);
// Return file result
return File(pdfbytes, System.Net.Mime.MediaTypeNames.Application.Pdf, "Report.pdf");
}
// Not exporting to PDF, show the view
return View(model);
}
@peterke91
Copy link

It returns the pdf, only it is empty, despite pdfbytes is not empty! any suggestions?
tried with stream also

Solved :P
Why i need to clear the doc after i already got the bytes? how can that affect the pdfbytes variable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment