ExpertPdf Anywhere ASP.NET Core samples · .NET 10 and .NET 11

ExpertPdf Anywhere - Partial Page Conversion with Html to Pdf Converter - C# / ASP.NET Sample

This sample shows how the html to pdf converter can be used to convert only a section of a web page using ExpertPdf Anywhere.

The section of the page that will be converted is identified by its element id (every engine) or by a CSS selector (RenderElementSelector, for example #content, .infobox or table.data).

Url:


Render element with ID:


Or render the element matched by the CSS selector:


C# code of this sample

Pages/PartialConversion.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using ExpertPdf.Anywhere.HtmlToPdf;
using ExpertPdf.Anywhere.PdfDocument;

namespace ExpertPdf.Samples.Pages
{
    public class PartialConversionModel : PageModel
    {
        public void OnGet()
        {
        }

        [BindProperty]
        public string TxtUrl { get; set; }

        [BindProperty]
        public string TxtElements { get; set; }

        [BindProperty]
        public string TxtSelector { get; set; }

        public IActionResult OnPost()
        {
            // instantiate a html to pdf converter object
            PdfConverter converter = new PdfConverter() { AllowLocalAccess = false };

            // specify the id of the section that will be converted to pdf
            if (!string.IsNullOrEmpty(TxtElements))
            {
                converter.RenderElementId = TxtElements;
            }

            // or a CSS selector; when both are set the selector wins
            if (!string.IsNullOrEmpty(TxtSelector))
            {
                converter.RenderElementSelector = TxtSelector;
            }

            // create a new pdf document converting an url
            Document doc = converter.GetPdfDocumentObjectFromUrl(TxtUrl);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Sample.pdf";
            return fileResult;

        }
    }
}