ПРОДУКТЫ   СКАЧАТЬ КУПИТЬ ПОМОЩЬ БЛОГ  О КОМПАНИИ  
 
Основные свойства
>>ASPX в PDF
Скачать пробную версию
Купить
Online-demo
Online-demo: ASPX в PDF
Документация
Новости
Обзоры и отзывы
How to convert ASPX page to PDF with forms filled by data using C# and .Net?.

"How to convert ASPX page to PDF with forms filled by data using C# and .Net?"

If you are looking for a solution to programmatically convert ASPX page with form filled by data to PDF in .Net and C#, you are in the right place!

How to convert ASPX page to PDF with forms filled by data using C# and .Net?
  • Various API to convert ASPX to PDF
  • Requires only .Net 2.0
  • Completely written in C#
  • Preserve all data filled by user in forms

PDF Vision .Net is what you need. It's a very simple in use and robust component! We offer your 100% .Net library, which will enhance your Web-Server ASP.Net or Windows Forms application to generate PDF documents on fly from ASPX and HTML.



Nuget   Скачать, 5.3.6(5 июнь, 2019)

Implementation and code sample

In this article we'll create a simple ASP.Net C# application with some forms controls (TextBox, ListBox and CheckBox) and the button "Print to PDF.

As you might agree, if you simply take an ASPX page and pass it to any PDF converter you will see the colorful result but all field forms and controls will have their default states. In other words, the basic problem in conversion of ASPX pages is to preserve all various data entered by an user.

Here you'll find the step by step answer how to solve this inconvenient problem:

The ready project you may find inside "PDF Vision .Net->Code Samples->CSharp->ASP.Net - Print ASPX to PDF".

Online Demo See the Online demo of ASPX to PDF.

Let's start:

First of all, create a new ASP.Net Web application. Next add contols inside form: TextBox, ListBox and CheckBoxes.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>How convert ASPX page to PDF with filled forms in C# and .Net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>How convert ASPX page to PDF with filled forms in C# and .Net</h1>
        <div>Fill some house description here:<br />
            <br />
            House space (m2):
            <asp:TextBox ID="txtHouseSpace" runat="server"></asp:TextBox>
            <br />
            <br />
            Number of floors:
            <asp:ListBox ID="lstFloorsNum" runat="server" Rows="1">
                <asp:ListItem Selected="True">1</asp:ListItem>
                <asp:ListItem>2</asp:ListItem>
                <asp:ListItem>3</asp:ListItem>
            </asp:ListBox>
            <br />
            <br />
            <asp:CheckBox ID="chkBathroom" runat="server" Checked="True" Text="Bathroom" />
 <asp:CheckBox ID="chkToilet" runat="server" Checked="True" Text="Toilet" />
 <asp:CheckBox ID="chkSwimmingPool" runat="server" Text="Swimming pool " />
        </div>
        <br />
            <p>
                <asp:Button ID="ButtonPDF" runat="server" onclick="GetPDF_Click" 
                    Text="Print to PDF" />
            </p>
        </div>
    </form>
</body>
</html>

The main idea is to get the state and values of all controls and store in a our custom class object before start conversion to PDF.

The next step is prepare the class to store all data and values from all of our controls (TextBoxes, ListBoxes and CheckBoxes). The next step is add this custom class to our application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// 
/// Summary description for HouseDescription
/// 
public class HouseDescription
{
	public HouseDescription()
	{
        HouseSpace = 120.0f;
        FloorsNumber = 2;
        IsBathroom = true;
        IsToilet = true;
        IsSwimmingPool = false;
	}
    public float HouseSpace { set; get; }
    public int FloorsNumber { set; get; }
    public bool IsBathroom { set; get; }
    public bool IsToilet { set; get; }
    public bool IsSwimmingPool { set; get; }
}

After that we've got the object with all data we need to place it inside Page.Application with unique ID. Thus all of our data will be available approx during 20 minutes if we know the unique ID. By the way you can customize the time of keeping objects inside Page.Application property.

Actually it's insecure to keep at server this data during 20 minutes, so the good practice is to remove the object from Application at once after PDF generation.

The final logic is recreate the page state by ID. In other words, the method which will convert ASPX to PDF will open the page with parameter, like a:

http://www.mysite.com/default.aspx?id=123456789

Knowing the ID you will find the necessary object of custom class and fill all controls: TextBoxes, CheckBoxes and ListBoxes.

This is rest of C# code (Default.aspx.cs):

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string id = Request.QueryString["id"];
        HouseDescription hd = null;


        if (id != null)
        {
            // Recreate the page state
            hd = (HouseDescription)Application[id];
            SetPageState(hd);
        }
        // First time loading. Set all to default.
        else
        {
            if (!IsPostBack)
                SetPageState(new HouseDescription());
        }

    }
    protected void GetPDF_Click(object sender, EventArgs e)
    {
        // 1. Save the current page state
        // 1.1. Create ID
        string id = Guid.NewGuid().ToString();

        // 1.2 Save the current state in the Application State.
        HouseDescription hd = GetPageState();
        Application[id] = hd;

        // 2. Create url
        string pageUrl = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
        string pageUrlWithQuerry = string.Format("{0}?id={1}", pageUrl, id);

        // 3. Get PDF
        SautinSoft.PdfVision v = new SautinSoft.PdfVision();

        // Set "Edge mode" to support all modern CSS.
        SautinSoft.PdfVision.TrySetBrowserModeEdgeInRegistry();
        byte[] pdf = v.ConvertHtmlFileToPDFStream(pageUrlWithQuerry);

        // 4. Show PDF result
        if (pdf != null)
        {
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = "application/PDF";
            //Response.AddHeader("Content-Disposition:", "attachment; filename=Result.pdf");
            Response.AddHeader("Content-Disposition:", "inline; filename=Result.pdf");
            Response.BinaryWrite(pdf);
            Response.Flush();
            Response.End();
        }
    }
    protected void SetPageState(HouseDescription hd)
    {
        txtHouseSpace.Text = hd.HouseSpace.ToString();
        lstFloorsNum.SelectedValue = hd.FloorsNumber.ToString();
        chkBathroom.Checked = hd.IsBathroom;
        chkToilet.Checked = hd.IsToilet;
        chkSwimmingPool.Checked = hd.IsSwimmingPool;
    }
    protected HouseDescription GetPageState()
    {
        HouseDescription hd = new HouseDescription();

        float houseSpace = 0f;

        if (float.TryParse(txtHouseSpace.Text, out houseSpace))
            hd.HouseSpace = houseSpace;

        int floorsNum = 1;
        if (Int32.TryParse(lstFloorsNum.SelectedValue, out floorsNum))
            hd.FloorsNumber = floorsNum;

        hd.IsBathroom = chkBathroom.Checked;
        hd.IsToilet = chkToilet.Checked;
        hd.IsSwimmingPool = chkSwimmingPool.Checked;
        return hd;
    }
}

The method "GetPageState" gets all data from controls and keeps it an object of a custom class.

The method "SetPageState" fills all page controls from an object of a custom class.

The method "GetPDF_Click" inserts the object of a custom class inside Page.Application using unique ID. Next this method calls the conversion to PDF, but this ID.

And the method "Page_Load" recreates the page state (fill all controls) in case of it met the ID and found an object of custom class corresponding to this ID.

See how this project works in real...



Преимущества PDF Vision .Net

  1. Мы гарантируем 100% качественную конвертацию HTML в PDF.

  2. Мы можем гарантировать 100% качество TIFF, JPG, PNG или любого изображения в формате PDF.

  3. PDF Vision .Net - это абсолютно автономный и независимый компонент C #. Дополнительно ничего не требует.

  4. Одноразовая оплата. Я плачу один раз и могу использовать «PDF Vision .Net» без каких-либо дополнительных сборов. Моя лицензия бессрочна.

  5. Наш компонент HTML to PDF / Images to PDF имеет разумную цену (от 239 долларов США).

  6. В качестве бонуса я получаю неограниченную техническую поддержку независимо от даты покупки.


Требования и техническая информация

    Требуется только .Net 2.0 или выше. Наш продукт совместим со всеми языками .Net и поддерживает все операционные системы, в которых может использоваться .NET Framework. Обратите внимание, что «PDF Vision .Net» полностью написано в управляемом C #, что делает его абсолютно автономным и независимой библиотекой.



Оптимальные цены

     Библиотека предлагает разработчикам высококачественное преобразование по оптимальным ценам. Основной интерес представляет то, что PDF Vision .Net дешевле, чем все его более или менее популярные конкуренты. Например, одна лицензия стоит $239 без каких-либо дополнительных сборов или платежей! Скачать


Скачать

Чтобы увидеть функциональность из первых рук, скачайте самые свежие «PDF Vision .Net» с примерами кода, 9.65 Mb.

 
Программы Скачать Помощь О компании
SautinSoft on Facebook SautinSoft on Twitter SautinSoft on Youtube Our Blog
Авторское право © 2002 - 2019 SautinSoft (начало с сайта sautin.com). Все права защищены.