NEWS

[C#] Hướng dẫn in hóa đơn Invoice từ Template HTML và xuất ra file PDF

[C#] Hướng dẫn in hóa đơn Invoice từ Template HTML và xuất ra file PDF
Đăng bởi: Thảo Meo - Lượt xem: 5391 08:36:35, 19/09/2022C#   In bài viết

Xin chào các bạn, bài viết hôm nay mình hướng dẫn các bạn cách xuất dữ liệu từ C# vào file template HTML trong lập trình C#, Winform.

[C#] Export data to HTML Template & Export PDF File

Ở bài này, mình sẽ sử dụng Template Engine Scriban để xuất dữ liệu, các bạn có thể tham khảo bài này ở web site của mình.

Video Demo ứng dụng Export Template C#:

  1. Đầu tiên, các bạn thiết kế 1 template invoice HTML, hoặc có thể tìm và download từ Internet về xong mình custom lại

template_invoice_html

Các bạn, thấy data mà chúng ta sẽ truyền vào được bọc bởi 2 dấu {{}}

Và dưới đây, là kết quả khi chúng ta đổ dữ liệu vào và xuất ra hóa đơn invoice template.

template_invoice_html_result

Và để xuất dữ liệu từ HTML sang PDF, bài viết mình sử dụng thư viện playwright để in.

Playwright là gì, thì bài viết tiếp theo, mình sẽ có bài viết về thư viện này.

Source code C#:

using Microsoft.Playwright;
using Scriban;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GeneratePDFFromTemplate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

      

        public List<Product> GetProducts() {

            var listProduct = new List<Product>();

            var product5 = new Product()
            {
                Name = "Bí kiếp tán gái họ Nguyễn",
                Price = 1000
            };
            var product1 = new Product()
            {
                Name = "Tự học C# trong 24h với Thảo Meo",
                Price = 158000
            };
            var product2 = new Product()
            {
                Name = "Lập trình Mobile với Flutter 3.3 ",
                Price = 255000
            };

            var product3 = new Product()
            {
                Name = "Cấu trúc dữ liệu & Thuật toán",
                Price = 99000
            };
            var product4 = new Product()
            {
                Name = "Tự học OPP trong Java",
                Price = 18000
            };

            listProduct.Add(product1);
            listProduct.Add(product2);
            listProduct.Add(product3);
            listProduct.Add(product4);
            listProduct.Add(product5);
            

            return listProduct;
            
        }

        public dynamic GenerateDataDemo() {
            var company = new
            {
                Name = txtCompany_name.Text,
                Phone = txtCompanyPhone.Text,
                Email = txtCompanyEmail.Text,
                Location = txtCompanyLocation
            };

            var customer = new
            {
                Name = txtCustomerName.Text,
                Mobile = txtCustomerMobile.Text,
                Email = txtCustomerEmail.Text,
                Address = txtCustomerAddress.Text
            };


            var fee = new
            {
                Total = GetProducts().Sum(x => x.Price).ToString("#,###"),
                Tax = "10 %",
                Transit = "35,000"
            };

            var data = new
            {
                Data = new {
                    Title = "Hóa đơn mua hàng",
                    Company = company,
                    Customer = customer,
                    NumInvoice = txtInvoiceNo.Text,
                    Products = GetProducts(),
                    Fee = fee,
                    Total = "2,585,000",
                    Date = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"),
                    Description = "Thanks for Shopping!"
                }
                  
            };

            return data;
        }

        private async void btnPrint_Click(object sender, EventArgs e)
        {
            var templateContent = File.ReadAllText("template_invoice.html");
            var template = Template.Parse(templateContent);

            var templateData = GenerateDataDemo();

            var pageContent = template.Render(templateData);
            File.WriteAllText("export.html", pageContent);
            Process.Start("export.html");

            var dataUrl = "data:text/html;base64," + Convert.ToBase64String(Encoding.UTF8.GetBytes(pageContent));
        
            var playwright = await Playwright.CreateAsync();
            var  browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
            {
                Headless = true,
            });

            var  context = await browser.NewContextAsync();
            var page = await context.NewPageAsync();
            await page.GotoAsync(dataUrl, new PageGotoOptions { WaitUntil = WaitUntilState.NetworkIdle });

            // Generate the PDF
            var output = await page.PdfAsync(new PagePdfOptions
            {
                Format = "letter", // or "letter"
                Landscape = true,
                Margin = new Microsoft.Playwright.Margin() {Top = "0", Right ="0", Bottom = "0", Left = "0" },
                Scale = 0.8f,
            });

            // Save the pdf to the disk
             File.WriteAllBytes("invoice.pdf", output);

            //File.WriteAllText("export.html", pageContent);
            Process.Start("invoice.pdf");
        }
    }

   public class Product
    {
        public string Name { get; set; }
        public int Price { get; set; }

        public string PriceAsString {
            get {
                return this.Price.ToString("#,###");
            }
           
        }

    }
}

Thanks for watching!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn in hóa đơn Invoice từ Template HTML và xuất ra file PDF
Đăng bởi: Thảo Meo - Lượt xem: 5391 08:36:35, 19/09/2022C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.