HiQPdf – Convert URL to PDF and Stream to Browser (ASP.NET)

 using System;

using System.Web;

using HiQPdf;


public class PdfController : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        // Example URL to convert — could come from query string or form input

        string targetUrl = "https://example.com";


        // Initialize the converter

        HtmlToPdf converter = new HtmlToPdf();


        // Optional: Set page size, orientation

        converter.Document.PageSize = PdfPageSize.A4;

        converter.Document.PageOrientation = PdfPageOrientation.Portrait;


        // Optional: Web page rendering options

        converter.Document.WebPageWidth = 1024;

        converter.Document.WebPageHeight = 0; // Auto height


        try

        {

            // Convert URL to PDF byte array

            byte[] pdfBytes = converter.ConvertUrlToMemory(targetUrl);


            // Set HTTP response headers for download

            Response.Clear();

            Response.ContentType = "application/pdf";

            Response.AddHeader("Content-Disposition", "inline; filename=GeneratedDocument.pdf");

            Response.AddHeader("Content-Length", pdfBytes.Length.ToString());


            // Write PDF to response stream

            Response.BinaryWrite(pdfBytes);

            Response.Flush();

            Response.End(); // End the response to prevent further rendering

        }

        catch (Exception ex)

        {

            Response.Write("Error generating PDF: " + ex.Message);

        }

    }

}



protected void btnGeneratePdf_Click(object sender, EventArgs e)

{

    string targetUrl = txtUrl.Text.Trim(); // Example textbox input


    HtmlToPdf converter = new HtmlToPdf();

    converter.Document.PageSize = PdfPageSize.A4;

    converter.Document.WebPageWidth = 1024;


    byte[] pdfBytes = converter.ConvertUrlToMemory(targetUrl);


    Response.Clear();

    Response.ContentType = "application/pdf";

    Response.AddHeader("Content-Disposition", "attachment; filename=site.pdf");

    Response.BinaryWrite(pdfBytes);

    Response.End();

}



object sender The control that raised the event (e.g., the clicked button)

EventArgs e Extra data about the event (empty in basic events)


No comments:

Post a Comment

HiQPdf – Convert URL to PDF and Stream to Browser (ASP.NET)

 using System; using System.Web; using HiQPdf; public class PdfController : System.Web.UI.Page {     protected void Page_Load(object sender,...

Best for you