MiziaQ
MiziaQ

Reputation: 137

ASP.NET web page to PDF

I looking for the easiest way to export the currently viewed asp.net web page to a PDF document using iTextSharp - it can be either a screenshot of it or passing in the url to generate the document. Sample code would be greatly appreciated. Many thanks in advance!

Upvotes: 2

Views: 6273

Answers (6)

carloswm85
carloswm85

Reputation: 2397

I've used https://github.com/webgio/Rotativa, rather easy to use.

You'll use ActionResult for generating a response pdf from a ASP.NET view.


Full Example

This methods should go inside the controller:

// MyController.cs
public virtual ActionResult PrintPdf(int requestId)
        {

            try
            {
                // Set pdf variables
                var date = DateTime.Now.ToString();
                var time = DateTime.Now.ToString();
                var filename = $"yourfile_{date}-{time}.pdf";

                // https://wkhtmltopdf.org/usage/wkhtmltopdf.txt
                // Send pdf to method
                return new ActionAsPdf("Pdf", new { id = requestId })
                {
                    FileName = filename,
                    PageOrientation = Rotativa.Options.Orientation.Portrait,
                    IsGrayScale = false,
                    IsJavaScriptDisabled = true,
                    MinimumFontSize = 16,
                    PageSize = Rotativa.Options.Size.A4,
                    PageMargins = new Rotativa.Options.Margins(20, 15, 20, 15),
                    CustomSwitches = string.Format("--footer-left \"File name: {0}\" "
                        + "--footer-right \"Page [page] of [toPage]\" "
                        + "--footer-font-size \"10\" "
                        + "--footer-line "
                        + "--footer-spacing \"4\"", filename)
                };
            }
            catch (Exception ex)
            {
                // ANY LOGGER YOU MAY USE           
            }
        }

        public virtual ActionResult Pdf(int id)
        {
            try
            {
                var yourViewModel = new YourViewModel();

                // Map main model
                var request = _service.GetItem(id);
                yourViewModel = _requestMapper.GetItem(request);
                ViewBag.Title = "Your Title";

                return View(yourViewModel);
            }
            catch (Exception ex)
            {
                // LOGGER
            }
        }

The following view pdf has the same name than the previous method. Keep that in mind.

This is how I called the method (I'm using T4MVC for the href, but that's not important really; use your own method for that):

<div class="d-flex gap-2 col-6">
    <a href="@Url.Action(MVC.Request.PrintPdf(@Model.Id))" role="button" class="btn btn-outline-danger w-100"><i class="fa fa-file-pdf-o me-2" aria-hidden="true"></i>PDF</a>
</div>

Your view:

// pdf.cstml
@model MiningTracker.Web.ViewModels.RequestViewModel
@{
    Layout = null; // Important for not rendering the main layout and getting a clead pdf
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <!-- Include this two references to styleshees, if necessary. -->
    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <link href='http://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'>
    <style>
        // I'm using this CSS code here because
        // I was not getting the correct style for
        // the generated file.
        body {
            font-family: 'Oswald', sans-serif !important;
        }

        td.myColor {
            color: red;
        }
    </style>
</head>
<body class="d-flex flex-column">
    @{
        <div>
            <img src="https://www.files.gob.ar/YourImage.png" alt="text" width="100%" />
        </div>

        <div class="container py-5">

            <h1 class="font-weight-bold text-center">Heading 1</h1>
            <h2 class="font-weight-bold text-center">Heading 2</h2>
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th scope="col">Header 1</th>
                            <th scope="col">Header 2</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <th scope="row">Row header 1</th>
                            <td class="myColor">@Model.myValue</td>
                        </tr>                       
                    </tbody>
                </table>
            </div>
        </div>
    }

</body>
</html>

Everything your need for working with Rotativa in the generation of a pdf using ASP.NET should be here.

You may have some troubles with the styles, as I did. They way I solved it is in this code.

Upvotes: 0

Winnovative
Winnovative

Reputation: 118

There is an example Convert the Current HTML Page to PDF on WInnovative website which does exactly this. The relevant C# code to convert the currently viewed asp.net web page to a PDF document is:

// Controls if the current HTML page will be rendered to PDF or as a normal page
bool convertToPdf = false;

protected void convertToPdfButton_Click(object sender, EventArgs e)
{
    // The current ASP.NET page will be rendered to PDF when its Render method will be called by framework
    convertToPdf = true;
}

protected override void Render(HtmlTextWriter writer)
{
    if (convertToPdf)
    {
        // Get the current page HTML string by rendering into a TextWriter object
        TextWriter outTextWriter = new StringWriter();
        HtmlTextWriter outHtmlTextWriter = new HtmlTextWriter(outTextWriter);
        base.Render(outHtmlTextWriter);

        // Obtain the current page HTML string
        string currentPageHtmlString = outTextWriter.ToString();

        // Create a HTML to PDF converter object with default settings
        HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

        // Set license key received after purchase to use the converter in licensed mode
        // Leave it not set to use the converter in demo mode
        htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";

        // Use the current page URL as base URL
        string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;

        // Convert the current page HTML string a PDF document in a memory buffer
        byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(currentPageHtmlString, baseUrl);

        // Send the PDF as response to browser

        // Set response content type
        Response.AddHeader("Content-Type", "application/pdf");

        // Instruct the browser to open the PDF file as an attachment or inline
        Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Convert_Current_Page.pdf; size={0}", outPdfBuffer.Length.ToString()));

        // Write the PDF document buffer to HTTP response
        Response.BinaryWrite(outPdfBuffer);

        // End the HTTP response and stop the current page processing
        Response.End();
    }
    else
    {
        base.Render(writer);
    }
}

Upvotes: 0

Smoothcity
Smoothcity

Reputation: 171

On a past project, we used Supergoo ABCPDF to do something like you need to and it worked quite well. You basicly feed it an url and it process the HTML page into a PDF.

On the downside, it's a licensed software with costs associated to it and we had some performance issues when exporting a lot of large PDF at the same time.

Hope this helps !

Upvotes: 1

Kumar
Kumar

Reputation: 1015

Give a try with PDFSharp (to generate PDF files at runtime), and it's Open Source library : http://pdfsharp.com/PDFsharp/index.php?option=com_content&task=view&id=27&Itemid=1

Alternative solution : http://www.bratched.com/en/component/content/article/76-how-to-convert-xhtml-to-pdf-in-c.html

Upvotes: 0

buda
buda

Reputation: 2372

It is not that easy (or i think so), i had same problem and i had to write code to generate exact page in pdf. It depends of page and used styles etc. So i create drawing of each element.

For some project i used Winnovative HTML to PDF converter but it is not free.

Upvotes: 0

Shoban
Shoban

Reputation: 23016

Adding to what Darin said in his comment.

You can try using wkhtmltopdf to generate PDF files. It takes URL as input. This is what I have used for my SO application so2pdf.

Upvotes: 0

Related Questions